Search code examples
phpyiiyii-cmodel

Yii - are most of functions in model files supposed to be static function?


I'm a Yii framework user.

mostly I define functions as public static function in my model files like the example function below.

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;      
}   

I wonder if I'm doing wrong.

are most of functions in model files supposed to be static function?

Please let me know if I'm doing or understanding wrong.

Thanks!!!


Solution

  • Yes, you are doing it wrong.

    Static methods are easy to call but have several architectural drawbacks, so generally speaking they should be used sparingly (or, even better: avoided altogether).

    In this instance there is no reason to use a static method and especially one that writes custom SQL. Use Yii's named scopes to accomplish the same goal:

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

    And then:

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