如何创建一个MVC模式的Joomla组件教程(十一) - 创建管理员界面Hellos Model

Hellos Model
Hellos Model非常简单,我们需要的是从数据库返回hellos列表,这通过getData()方法实现。
还有一个_getList()的保护方法,这个方法用来简化从数据库返回数据的任务,我们只是简单的传递query并且返回记录列表。

也许以后某个时候,我们在另一个方法中使用这个查询,因而我们创建了一个私有方法 _buildQuery() ,这个方法返回query,并且传递给_getList(). 这样可以集中在一处来修改查询语句。

 getData() 和 _buildQuery() 方法是必须需要的:

_buildQuery() 仅仅是返回语句,代码如下:

/**
 * Returns the query
 * @return string The query to be used to retrieve the rows from the database
 */
function _buildQuery()
{
    $query = ' SELECT * '
           . ' FROM #__hello '
    ;

    return $query;
}

getData() 将用这个sql从数据库返回数据. 也许我们需要两次获取同样数据,重复运行查询是非常浪费的,因而,我们保存结果在一个保护属性_data中,这样只需查询一次就可以了。


以下是 getData() 方法:

/**
 * Retrieves the hello data
 * @return array Array of objects containing the data from the database
 */
function getData()
{
    // Lets load the data if it doesn't already exist
    if (empty( $this->_data ))
    {
        $query = $this->_buildQuery();
        $this->_data = $this->_getList( $query );
    }

    return $this->_data;
}

完整model代码如下(models/hellos.php):

<?php
/**
 * Hellos Model for Hello World Component
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 * @license        GNU/GPL
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

/**
 * Hello Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class HellosModelHellos extends JModel
{
    /**
     * Hellos data array
     *
     * @var array
     */
    var $_data;

    /**
     * Returns the query
     * @return string The query to be used to retrieve the rows from the database
     */
    function _buildQuery()
    {
        $query = ' SELECT * '
            . ' FROM #__hello '
        ;
        return $query;
    }

    /**
     * Retrieves the hello data
     * @return array Array of objects containing the data from the database
     */
    function getData()
    {
        // Lets load the data if it doesn't already exist
        if (empty( $this->_data ))
        {
            $query = $this->_buildQuery();
            $this->_data = $this->_getList( $query );
        }

        return $this->_data;
    }
}

posted on 2009-12-26 22:01  14的路  阅读(441)  评论(0编辑  收藏  举报

导航

友情链接:源码下载