Skip to content

Instantly share code, notes, and snippets.

@geerteltink
Created November 1, 2016 20:33
Show Gist options
  • Save geerteltink/f10292fab031a0088632f52b82a5f663 to your computer and use it in GitHub Desktop.
Save geerteltink/f10292fab031a0088632f52b82a5f663 to your computer and use it in GitHub Desktop.
ZF3 standalone EventManager with LazyListeners
<?php
use App\Infrastructure\EventManager\Listener\AnotherListener;
use App\Infrastructure\EventManager\Listener\UserLoginListener;
use Zend\EventManager\LazyListenerAggregate;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\ServiceManager\ServiceManager;
chdir(dirname(__DIR__));
require __DIR__ . '/vendor/autoload.php';
$config = [
'dependencies' => [
'factories' => [
UserLoginListener::class => InvokableFactory::class,
AnotherListener::class => InvokableFactory::class,
],
'aliases' => [
],
],
'zend-eventmanager' => [
'definitions' => [
[
'listener' => UserLoginListener::class,
'method' => 'notifyUser',
'event' => 'user.login',
'priority' => 100,
],
[
// This listener shouldn't be initialized
'listener' => AnotherListener::class,
'method' => 'notifyUser',
'event' => 'user.logout',
'priority' => -100,
],
],
],
];
// Load configuration
$dependencies = $config['dependencies'];
// Inject config as a service
$dependencies['services']['config'] = $config;
$container = new ServiceManager($dependencies);
$eventManager = new \Zend\EventManager\EventManager();
$aggregate = new LazyListenerAggregate(
$container->get('config')['zend-eventmanager']['definitions'],
$container
);
$aggregate->attach($eventManager);
$eventManager->trigger('user.login', null, ['userId' => 1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment