0 追蹤者

建立近期評論 Portlet

在本節中,我們將建立最後一個 portlet,用於顯示近期發佈的留言列表。

1. 建立 RecentComments 類別

我們在檔案 /wwwroot/blog/protected/components/RecentComments.php 中建立 RecentComments 類別。檔案內容如下

Yii::import('zii.widgets.CPortlet');
 
class RecentComments extends CPortlet
{
    public $title='Recent Comments';
    public $maxComments=10;
 
    public function getRecentComments()
    {
        return Comment::model()->findRecentComments($this->maxComments);
    }
 
    protected function renderContent()
    {
        $this->render('recentComments');
    }
}

在上方我們調用了 Comment 類別中定義的 findRecentComments 方法,如下所示:

class Comment extends CActiveRecord
{
    ......
    public function findRecentComments($limit=10)
    {
        return $this->with('post')->findAll(array(
            'condition'=>'t.status='.self::STATUS_APPROVED,
            'order'=>'t.create_time DESC',
            'limit'=>$limit,
        ));
    }
}

2. 建立 recentComments 視圖

recentComments 視圖儲存在檔案 /wwwroot/blog/protected/components/views/recentComments.php 中。它僅顯示 RecentComments::getRecentComments() 方法傳回的每個留言。

3. 使用 RecentComments Portlet

我們修改版面配置檔案 /wwwroot/blog/protected/views/layouts/column2.php 以嵌入最後一個 portlet,

......
<div id="sidebar">
 
    <?php if(!Yii::app()->user->isGuest) $this->widget('UserMenu'); ?>
 
    <?php $this->widget('TagCloud', array(
        'maxTags'=>Yii::app()->params['tagCloudCount'],
    )); ?>
 
    <?php $this->widget('RecentComments', array(
        'maxComments'=>Yii::app()->params['recentCommentCount'],
    )); ?>
 
</div>
......

發現錯字或您認為此頁面需要改進?
在 github 上編輯 !