Search code examples
phpcakephpcakephp-2.3

Registering a model as an event listener


I'd like to know if this is a good idea to register a Model class as an CakeEventListener inside the Model's PHP file.

For example, if I created a Model called Document that implements the listener, and at the bottom of the Document.php there I register it as a listener.

class Document extends AppModel implements CakeEventListener
{
   .....
}

CakeEventManager::instance()->attach(ClassRegistery::init('Document'));

My question is about nexted calls to ClassRegistery::init('Document') and if the above would cause two instances of Document to be created.

For example, let's say I have the following in my controller.

class DocumentsController extends AppController
{
     public function index()
     {
         $model = ClassRegistery::init('Document');
         .....

How many times is Document instantiated?

  • The first call to ClassRegistery::init('Document') from the controller loads the Document.php file.
  • Wouldn't there be a second call to ClassRegistery::init('Document') from the bottom of Document.php befoe the first call has finished?

Would this somehow strew up the registry in CakePHP?


Solution

  • It shouldn't be a problem. ClassRegistry::init() only instantiates the object once. Subsequent calls to init() return the existing object.

    I would, however, suggest registering the listener in Document's __construct function. This feels cleaner because we aren't mixing self-executing PHP with the class file. It also allows possible injection later on which would be useful for unit tests.