How To Attach Same Behavior On Multiple Models

Hello everyone,

Let’s assume that our project has these 3 models:

  • Product

  • Category

  • Brand

All the above models have a slug column. I’m using http://www.yiiframework.com/extension/yiibehaviorsluggable/ extention in order to generate the slugs automatically by adding this simple piece of code in each model:




/**

 * Behaviors for this model

 */

public function behaviors(){

  return array(

    'sluggable' => array(

      'class'=>'ext.behaviors.SluggableBehavior.SluggableBehavior',

      'columns' => array('name'),

      'unique' => true,

      'update' => true,

    ),

  );

}



My question is, can I avoid adding this same piece of code in all my models? Can I add it somewhere where it applies to all models or to models that I specify? If so, how can it be done?

Create a class that extends CActiveRecord and add this behaviour to it. Let all your models extend this new class.

Thanks Ronald! You really helped me make it work.

I also read this: http://www.yiiframework.com/wiki/121/extending-common-classes-to-allow-better-customization/

If anyone’s interested, here’s how I did it:

I created a file called MyActiveRecord.php in /protected/components with the following code:




<?php


class MyActiveRecord extends CActiveRecord

{

	/**

	 * Behaviors for this model

	 */

	public function behaviors(){

	  return array(

		'sluggable' => array(

		  'class'=>'ext.behaviors.SluggableBehavior.SluggableBehavior',

		  'columns' => array('name'),

		  'unique' => true,

		  'update' => true,

		),

	  );

	}

}



Then in each model I want to apply the slug behavior, I edit it and instead of extending CActiveRecord, it extends MyActiveRecord Class, which also extends CActiveRecord.

It works just great! Thanks again!

Yes basically its a good approach to extend CactiveRecord class and do the required changes in that class and change the extended class in your model class where ever you want…:)

Thanks codesutra for letting me know it’s a good approach!