如何创建一个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;
    }
}

转载于:https://www.cnblogs.com/vicenteforever/articles/1633011.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值