How to attach a CActiveRecord behavior to all models


I have written an extension for CActiveRecordBehavior which allows a soft delete (changes a ‘deleted’ column to 1 and back again to 0)

How can I get this behavior added to every model rather than having to include it in each model declaration?



Define a behaviors() method inside your AR class:

public function behaviors()


    return array(








perfect, cheers

if you extend CActiveRecord and attached that behaviour to it, than in your models you will extend your customized activerecord object it will do it.

That’s the right way to go, instead of modifying a core class within the framework folder. The first reason of leaving the framework folder and the original classes intact, is that you can be able to use the SAME code for several projects, and the distinctive code of each project should be inside each project’s folder, not in the common core code. The second reason, is that if you want that another programmer comes in the future and wants to work with your code, he can trust that he is standing on the basic framework, and PREDICT your code. In general it is a good policie to write code thinking that it will be read by others. The third reason is that you must be able to UPGRADE to the next Framework’s version whenever you want, without having to repeat over and over modifications in the core classes. Such extension can be put in the protected/components folder, for example:

-----------------------------------file: protected/components/MyCustomizedActiveRecord.php---------

class MyCustomizedActiveRecord extends CActiveRecord {

public function beforeDelete () {




And afterwards, do a massive search-replace operation in your models folder like the following:


extends CActiveRecord ==>to be replaced by==> extends MyCustomizedActiveRecord


(there’s automated software to do such massive replacements)

I wanted to point that out for future users, knowing that the forum is old. I’m pretty sure it will help future programmers.

Best regards from Colombia, and congratulations to the authors of this great framework,

Investigación y Programación