简体   繁体   中英

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

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM