I would like to implement listener, which is not required on every request (that is the purpose of LazyListener). But I can’t figure out working example. Here is the code:
<?php
namespace Order;
use Laminas\Config;
use Laminas\Mvc\MvcEvent;
use Laminas\EventManager\LazyListenerAggregate;
class Module
{
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$eventManager = $application->getEventManager();
// demo lazy
$definition = array(
'listener' => Event\DemoLazyListener::class,
'method' => 'onEchoVal',
'event' => 'echoVal',
'priority' => - 100
);
$aggregate = new LazyListenerAggregate([$definition], $application->getServiceManager());
$aggregate->attach($eventManager);
// dump($aggregate); exit;
}
.....
}
Listener is class with factory to access services later.
<?php
namespace Order\Event;
use Laminas\ServiceManager\ServiceLocatorInterface;
use Laminas\EventManager\EventInterface;
class DemoLazyListener
{
public $serviceManager;
public function __construct(ServiceLocatorInterface $serviceManager)
{
$this->serviceManager = $serviceManager;
}
public function onEchoVal(EventInterface $event)
{
$param = $event->getParam('param');
$writer = new \Laminas\Log\Writer\Stream(__DIR__ . '/../../../../data/log/event_demo.log');
$logger = new \Laminas\Log\Logger();
$logger->addWriter($writer);
$logger->info('Param ' . $param . '.');
}
}
Event is triggered in controller action.
$this->getEventManager()->trigger('echoVal', null, [
'param' => 'demo'
]);
When I dump the LazyListenerAggregate the listener key is null. I’m not sure if this is not the case.
Thank you in advance for help.