Last active 1729626733

Example of a short-circuiting event listener in Zend Framework

matthew's Avatar matthew revised this gist 1729626733. Go to revision

No changes

matthew's Avatar matthew revised this gist 1729619964. Go to revision

No changes

matthew's Avatar Matthew Weier O'Phinney revised this gist 1503000134. Go to revision

1 file changed, 41 insertions

Module.php(file created)

@@ -0,0 +1,41 @@
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 + }
Newer Older