Extend CActiveRecord for all models?

Is it possible to extend CActiveRecord to add a behavior to be applied across all models?

The idea is to avoid having to edit every single model, as I’d rather edit 1 file than 90.


Ah, looks like this should suffice (editing the config to specify a behavior to be loaded)


Hmm, I was hoping to get it working as follows (by editing config/main.php), but apparently no go?

// This is the main Web application configuration. Any writable

// CWebApplication properties can be configured here.

return array(

    // ...

    // application components


        // ...

        // uncomment the following to use a MySQL database


            'connectionString' => 'mysql:host=localhost;dbname=noneya',

            'emulatePrepare' => true,

            'username' => 'noneya',

            'password' => 'noneya',

            'charset' => 'utf8',















        // ...


    // ...


You specified two behaviors to be attached to the "db" application component. As mentioned in the guide, for CActiveRecord you have to override the behaviors() method. You can do that in a base controller you create, but you still have to change your models so they extend from your base controller.

(not tested)


Thanks Tommy, but I was hoping to avoid that route, as that then requires that I extend the custom class in every model (means editing every model).

Does anyone have any thoughts on how to attach the behaviors to models on-the-fly (or a hack for the config) to easily add the behaviors?


Have you looked at attachBehaviors ? http://www.yiiframework.com/doc/api/CComponent#attachBehaviors-detail


I would also suggest to have your own base AR class. The change is very easy if you can do a global string replacement.

If you have the oportunity to be on a linux console:

cd protected/models

sed -i 's/CActiveRecord/MyARBaseClass/' *.php

Thanks notzippy, I’ll check that out for future reference

Thanks qiang and Mike, I went ahead and extended CActiveRecord, but I would like to go on the record as saying that being able to specify AR behaviors from main.php would be awesome :wink: