| 1 | <?php |
| 2 | |
| 3 | // In a module class somewhere... |
| 4 | use Zend\EventManager\LazyListener; |
| 5 | use Zend\Mvc\MvcEvent; |
| 6 | |
| 7 | class Module |
| 8 | { |
| 9 | public function onBootstrap(MvcEvent $e) |
| 10 | { |
| 11 | $app = $e->getApplication(); |
| 12 | $services = $app->getServiceManager(); |
| 13 | $events = $app->getEventManager(); |
| 14 | |
| 15 | $listener = new LazyListener([ |
| 16 | 'listener' => YourShortCircuitingListener::class, |
| 17 | 'method' => '__invoke', |
| 18 | ], $services); |
| 19 | |
| 20 | $events->attach(MvcEvent::EVENT_ROUTE, $listener, PHP_INT_MAX); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | // And now for the listener... |
| 25 | class YourShortCircuitingListener |
| 26 | { |
| 27 | public function __invoke(MvcEvent $e) |
| 28 | { |
| 29 | $request = $e->getRequest(); |
| 30 | if (/* some criteria that, if met, means we should continue normal operation */) { |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | // At this point, we know we want to short-circuit |
| 35 | $response = $e->getResponse(); |
| 36 | |
| 37 | // populate the response |
| 38 | |
| 39 | return $response; |
| 40 | } |
| 41 | } |
matthew / zend-eventmanager short-circuiting listener
Last active 17 hours ago
Example of a short-circuiting event listener in Zend Framework