我正在用Yii创建一个新的Portlet。此小部件显示问题的最新评论。我想要显示这只有当问题有评论和不显示它(事件标题),如果问题没有任何评论。
所以我在视图文件中的psudo代码如下:
检查评论数进程:
<?php
$countIssue = count($model->issues);
$i = 0; $j = 0;
while($i < $countIssue)
{
$j += $model->issues[$i]->commentCount;
$i ++;
}
?>
if ($countIssue >0 ) {
if ($j >0)
Display the widget
}
Else
Don't display the widget我只是想知道我的代码是否适用于MVC模型。你能给我指个方向吗?我应该将注释过程的检查号带到模型还是控制器,或者上面的MVC模式可以吗?
谢谢!
发布于 2012-08-09 21:39:32
首先,我会将此逻辑移到portlet类(扩展CPorlet的类)的run()方法中。
接下来,我将在Issue类中定义一个STAT relation。此关系仅用于计算评论,并允许您使用如下语句:
$issue = Issue::model()->findByPk($issue_id);
// $comments_count below is exactly what you would expect... .
$comments_count = $issue->commentsCount;最后,结合所有这些,我推荐在portlet的run()方法中使用如下方法:
If ($someIssue->commentsCount > 0) {
// do something and in the end, when you want to render the portlet, you do...
$this->render("view_file_name");
}发布于 2012-08-09 22:19:00
我认为有许多MVC友好的方法可以做到这一点,主要的想法是将数据逻辑放在模型中,然后通过控制器处理请求,而理想情况下视图应该只用于显示目的。
就我个人而言,我将使用Yii named-scopes (最初来自Rails)来实现最新的过滤器,如下所示:
模型:
class Comment extends CActiveRecord
{
......
public function scopes()
{
return array(
'recently'=>array(
'order'=>'create_time DESC',
'limit'=>5,
),
);
}
}要获得列表注释(如果只有问题有一些注释),可以在控制器中执行以下操作
if($issue->comments)
$isseComments = Comment::model()->recently()->findAll(); //using the named scope to the recent ones only
$this->render('your_action',array(
.....
'issue' => $issue,
'issueComments'=>$isseComments,
));而您的视图将保持整洁:
if($issueComments > 0)
//Display the widget
else
// Don'thttps://stackoverflow.com/questions/11880667
复制相似问题