For some models, we have soft deletion implemented using a valid boolean in MySQL.
In the class, the scopes method is defined as follows:
public function scopes() {
return array(
'valid'=>array(
'condition'=>"t.valid=1",
)
);
}
This is so that when we load a model we can call the scope to make it include only valid (not deleted) models alongside the other find criteria, or whatever it happens to be.
This isn’t very DRY and I am wondering if there is an alternative way of achieving the same thing, that could perhaps be applied to an interface, the abstract Model class that all models derive from, or, if using 5.4, a trait.
Yii has a feature called Behaviors
that is similar to php 5.4 traits but works with earlier versions too.
SoftDeleteBehavior.php:
Then i have this class to apply deafultscope from behaviors:
ActiveRecord.php (i ofcourse have more methods in this class, downside is that you need to call parent method if you need to extend the method):
And then you use it in your Models:
PROTIP: you can specify your own ActiveRecord class when you generate models with gii