To make events work you first must register the event handling logic with one of the event managers.
@Ermias shows an example of how that can be done. First he creates a class that holds the logic that will be executed when the event is triggered, then he makes sure that logic is known to the event system.
He performs that second step with this code in his bootstrap:
use Cake\Event\EventManager;
use App\Event\BlogsListener;
$myevent = new BlogsListener();
EventManager::instance()->on($myevent);
When the EventManager receives the instance of the BlogsListener class, it will use the array returned by implementedEvents()
to identify all the event handling methods and will register them by name; the keys of the array provides the event names, the values are the names of the methods that will run when the event is triggered.
Any class can be sent to the event manager as long as it has the implementedEvents()
method to guide the event registration process.
In fact, Views, Controllers and Table classes are automatically sent to the event manager for analysis and registration of their events.
So, if you know that a particular event is only triggered by one Controller or one Table, you can write the event handling method in that class and let it be automatically registered by Cake.
In short, you can register your listeners at any time and in as broad or finite a scope as you want. But you must register them before you trigger them.
There are several independent event managers and you may register your events with any you choose. This detail is covered here.
With all this in place your code can, at any time, trigger an event. Again as @Ermias has illustrated:
$event = new Event('Controller.Blogs.check', $this)
$this->geteventManager()->dispatch($event);
Some details here are worth discussion.
The event manager distpatch()
takes an Event object. That object is constructed from three arguments:
- the name of the event (a ‘key’ from
implementedEvents()
as mentioned earlier)
- the current object (to provide full context for the event handler logic)
- an array of other data you want in your event handling logic.
This event is then sent to one of the EventManagers. I have not verified this for myself, but given that the Event is passed to a specific EventManager, and there are several different instances of that class, you probably have to insure your event is registered on the manager you eventually trigger.
You’ll have to confirm that. It might be that ALL managers get notified, but I just don’t know.