Yii - 模型文件中的大多数函数都应该是静态函数吗?

时间:2013-09-03 07:07:57

标签: php yii yii-cmodel

我是Yii框架用户。

我主要在我的模型文件中将函数定义为公共静态函数,如下面的示例函数。

public static function getTrashedPostCount(){           
    $connection=Yii::app()->db;     
    $sql = "SELECT COUNT(publish_status)
                FROM {{post}}
                WHERE publish_status = 'trash'";              
    $command=$connection->createCommand($sql);
    $postCount = $command->queryScalar();
    return $postCount;      
}   

我想知道我做错了。

模型文件中的大多数函数应该是静态函数吗?

如果我在做或理解错误,请告诉我。

感谢!!!

2 个答案:

答案 0 :(得分:7)

是的,你做错了。

静态方法很容易调用,但有一些架构上的缺点,所以一般来说它们应该谨慎使用(或者更好:完全避免使用)。

在这种情况下,没有理由使用静态方法,尤其是编写自定义SQL的方法。使用Yii的named scopes来实现相同的目标:

class Post extends CActiveRecord
{
    public function scopes()
    {
        return array(
            'trashed'=>array(
                'condition' => "publish_status = 'trash'",
            ),
        );
    }
}

然后:

$trashedCount = Post::model()->trashed()->count();

答案 1 :(得分:2)

您不想使用静态方法,因为那时您放弃了许多不错的yii功能,例如默认范围,事件等。

如果可能,您也不希望使用原始SQL,因为这可能会使转换到其他数据库系统变得复杂。

所以你想做这样的事情:

public function getTrashedPostCount() {
    return $this->countByAttributes(array('publish_status' => 'trash'));
}

您可以看到您正在使用 CActiveRecord countByAttributes 方法,而且好处是默认范围会自动应用,因此您无需保重那个。我建议您花一些时间来了解可供您使用的方法。

然后查询这样的已删除帖子的数量:

Posts::model()->getTrashedPostCount()

甚至使用一些魔法

Posts::model()->trashedPostCount
相关问题