This is supposed to clarify what's already in the official documentation at https://book.cakephp.org/3/en/core-libraries/events.html
-
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 tosrc/Event/ExampleListener.php
-
Make this listener class have
implementedEvents()
method that looks like:public function implementedEvents() { return array( 'Model.afterSave' => 'exampleAfterSave', ); }
Hooking to
Model.afterSave
will triggerexampleAfterSave
on every model throughout your application that has this listener attached. See below on how to filter. -
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… }
-
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 theinitialize()
method:public function initialize(array $config) { //… $listener = new \App\ExampleCustomClasses\ExampleListener(); $this->getEventManager()->on($listener); }