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

1.4k views Asked by At

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!!!

2

There are 2 answers

4
Jon On BEST ANSWER

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();
3
Martin Komara On

You don't want to use static methods, because then you are giving up many nice yii features such as default scopes, events etc.

Also you don't want to use raw SQL if possible, because that might complicate transition to other database system.

So you want to do something like this instead:

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

You can see that you are using CActiveRecord's countByAttributes method and the nice thing is that default scope is applied automatically, so you don't need to take care of that. I recommend that you take some time to learn what methods are available for you to use.

You then query for number of trashed posts like this:

Posts::model()->getTrashedPostCount()

Or even by using some magic

Posts::model()->trashedPostCount