How to get a list of attached behaviors?

I would like to get a list of attached behaviors. How should I do that?

$class->behaviors() seams to return empty array all the time. I’ve tried on CActiveRecord when I have defined behavior for it.

In the documentation behaviors is marked as property, not as method.

Try $class->behaviors without brackets or with $class->getBehaviors()

I am talking about this one: http://www.yiiframework.com/doc/api/1.1/CModel/#behaviors-detail

Well, that page describes a method that allows you to specify the behaviors that a model should have. It does NOT describe a method that allows you to get a list of currently attached behaviors.

That’s because, to my knowledge, there is no such method - and I looked into it pretty thoroughly. There is a workaround, however.

  • First, make sure all your Controller (or Model) classes derive from your own base class, as described here: (Yii doesn’t allow me to post links yet, new user blabla)

www.yiiframework.com/wiki/121/extending-common-classes-to-allow-better-customization/

  • Then, make sure that class includes a public/protected/private property, called ‘_behaviors’.

  • Override the attachBehavior method, and use $this->_behavior to store the behavior that is being attached.

  • Implement a ‘getBehaviors()’ method that returns the value of $this->_behaviors

  • If all your controller classes extend MyController, you can now use the ‘getBehaviors()’ if necessary.

Your final code should look something like this:




class MyController extends CController {

	public $_behaviors;


	public function attachBehavior($name, $behavior) {

		return $this->_behaviors[$name] = parent::attachBehavior($name, $behavior);

	}


	public function getBehaviors() {

		return $this->_behaviors;

	}

}



You can also do a similar thing for CModel I guess, or - even better - for CComponent.

Unfortunately I am working on an extensions, and I can’t do these customizations because have to work with all kind of components. So it must be free from any custom modifications. Thanks for the effort though.