I’m currently trying to learn and understand the CakePHP even system.
I have a working controller which processes an order.
After that order has been placed I would like to trigger an event.
I started with http://book.cakephp.org/3.0/en/core-libraries/events.html
-
In my Model called SoldServicesTable I have a function called place()
At the end of that function I added:$event = new Event('Model.SoldServices.afterPlace', $this, [ 'order' => $cart, 'orderid' => $orderid ]); $this->eventManager()->dispatch($event);
-
under src/Event I created a listener class:
namespace App\Event;
use Cake\Log\Log;
use Cake\Event\EventListenerInterface;
class SoldServicesListener implements EventListenerInterface
{public function implementedEvents()
{
return array(
‘Model.SoldServices.afterPlace’ => ‘CreateServices’,
);
}public function CreateServices($event, $entity, $options)
{
//debug($event);
//debug($entity);
Log::write(
‘info’,
'A new post was published with id: ’ );
}
}</code>
-
(this is where I’m stuck) the cake PHP book states to attach the listener object to the event manager:
// Attach the UserStatistic object to the Order’s event manager
$statistics = new UserStatistic();
$this->Orders->eventManager()->on($statistics);
I can not seem to find where exactly to put this piece of code.
I tried to add it to the models initialize() function like this:
$listener = new \App\Event\SoldServicesListener();
$this->eventManager()->on($listener);
But events are not being triggered. In older sample code I can only find examples on how to use the event system with a Global listener which I do not want to do.
Could somebody please give me a hint on where exactly to put the code to attach the listener object to the event manager?