Registered event handlers and behaviors stored in a file

If I remember well, elsewhere in the forum (about Events 2.0) it was talked about a class having a static list of registered event handlers.

Qiang was at that time not convinced we needed that option. I think we do.

Even worse: I think we should also have a static list of behaviors (or maybe we should only have a static list of behaviors and not event handlers).

Example:




class CActiveRecord extends CModel

{

	function behaviors() { ... }		// these are the instance behaviors, i.e. installed on instantiation


	static function attachClassBehaviors() {...}		// add a class behaviors.


	static function on(trigger, handler) { ... }		// add a trigger to the static list of event handlers

}



Why do we need this?

This makes it possible to store class behaviors and event handlers that need to be attached in a file. This file can be used by the autoloader to add the behaviors and event handlers to the static list of a class the moment it is loaded.

Example of the file:




return array(

	'CActiveRecord' => array(

		'behaviors' => array(

			'myBehavior', 

			'hisBehavior', 

			'ourBehavior' => array(

				'class' => 'path.to.ourBehavior',

				'param1' => 'value1'

			)

		),


		'events' => array(

			'onBeforeSave' => array(

				function($event) {...},		// register anonymous function

				array('CMyClass', 'methodName'),       // register a static method

			),

			'onBeforeDelete' => array(

				...

			)

		)

	),


	'path.to.MyClass' => array(

		...

	)

);



The advantage in this is that it is possible to interfere with existing classes that we have no control over as they are developed by a third party.

This also may even be a (partial) solution to modules being able to communicate with eachother.

Real case scenario:

I developed this marvelous user module that everybody wants. I instantiated all my db models from CActiveRecord.

Now someone wants to use this module in an environment where he needs tracing of changes made to a table row. He’d thus wants my module but with all models having the CTimestampBehavior added. In the current situation he’d have to edit the code for this user module, while in my proposal he’d just have to register the behavior with CActiveRecord.