Answer the question
In order to leave comments, you need to log in
How to use events in ZF2/3?
Good day!
Please tell me how to subscribe to events and in what place. There are a lot of examples on the Internet with Foo bar, but they do not give any idea how to use it in real projects.
For example, I have an order change. In the bootstrap of the module, I did this
$sharedEventManager->attach(
Mapper\Order::class,
AbstractMapper::EVENT_INSERT_ENTITY,
function ($e) use ($serviceManager) {
/** @var \Office\Service\Order $orderService */
$orderService = $serviceManager->get(Service\Order::class);
$entity = $e->getParam('entity');
if ($entity) {
$orderService->addOrderLog($entity, Entity\Order\LogAction::CREATED);
}
}
);
/**
* @param EventManagerInterface $events
*/
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(
Order::EVENT_ERROR_CONFIRM_ORDER, [
$this,
'sendErrorConfirmOrder'
]
);
$this->listeners[] = $events->attach(
Order::EVENT_CONFIRM_ORDER, [
$this,
'okConfirmOrder'
]
);
}
$class->getEventManager()->attach($agregator);
Answer the question
In order to leave comments, you need to log in
You need to understand the main point of events in ZF3 - you need to create a SEPARATE INDIVIDUAL EventManager instance for each group of events.
... and then retrieve events from that same INDIVIDUAL EventManager*.
That is, a feature with one EventManager for the ENTIRE project is a dead end.
Firstly, the task of events is just going to the moon .
On events, you implement either an extension of the main functionality or the work of things that are optional for the main flow.
This will remove a lot of headaches both now during debugging and in the future.
Secondly, it is correct to subscribe to events at the stage of application initialization.
This can be an application bootstrap, a module bootstrap, at the time of initialization of a particular service.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question