Last active 1729626733

Example of a short-circuiting event listener in Zend Framework

Revision 11574c4480e3cdb39b2f6082a91d3e39e6a6ce4c

Module.php Raw
1<?php
2
3// In a module class somewhere...
4use Zend\EventManager\LazyListener;
5use Zend\Mvc\MvcEvent;
6
7class 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...
25class 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}