The very basics of getting started with CakePHP events

in CakePHP


This is supposed to clarify what's already in the official documentation at https://book.cakephp.org/3/en/core-libraries/events.html

  1. Create a listener. Can be a separate arbitrary class, or an existing class in the MVC scheme of things. (Deciding what would be a good place for an event listener?) Either way, it has to implement \Cake\Event\EventListenerInterface. Lets say it was a standalone class and it went to src/Event/ExampleListener.php

  2. Make this listener class have implementedEvents() method that looks like:

    public function implementedEvents()
    {
        return array(
            'Model.afterSave' => 'exampleAfterSave',
        );
    }

    Hooking to Model.afterSave will trigger exampleAfterSave on every model throughout your application that has this listener attached. See below on how to filter.

  3. Add exampleAfterSave():

    public function exampleAfterSave($event, $entity, $options)
    {
        // Skip if triggered not on the model we need
        if ($event->getSubject()->getAlias() !== 'Users') {
            return true;
        }
        // Do something…
    }
  4. Finally, the model that you would like to listen to needs to ne aware of that. In your e.g. src/Model/Table/UsersTable.php, attach the listener to the initialize() method:

    public function initialize(array $config)
    {
        //…
        $listener = new \App\ExampleCustomClasses\ExampleListener();
        $this->getEventManager()->on($listener);
    }
#cakephp #best-practices #decoupling