Dispatcher Filters
There are several reasons to want a piece of code to be run before anycontroller code is executed or right before the response is sent to the client,such as response caching, header tuning, special authentication or just toprovide access to a mission-critical API response in lesser time than a completerequest dispatching cycle would take.
CakePHP provides a clean interface for attaching filters to the dispatchcycle. It is similar to a middleware layer, but re-uses the existing eventsubsystem used in other parts of CakePHP. Since they do not work exactlylike traditional middleware, we refer to them as Dispatcher Filters.
CakePHP comes with several dispatcher filters built-in. They handle commonfeatures that all applications are likely to need. The built-in filters are:
- checks whether the request is referring to a themeor plugin asset file, such as a CSS, JavaScript or image file stored in either aplugin’s webroot folder or the corresponding one for a Theme. It will serve thefile accordingly if found, stopping the rest of the dispatching cycle:
RoutingFilter
applies application routing rules to the request URL.Populates$request->getParam()
with the results of routing.ControllerFactory
uses$request->getParam()
to locate the controller thatwill handle the current request.LocaleSelector
enables automatic language switching from theAccept-Language
header sent by the browser.
- DispatcherFactory::add('Routing');
- DispatcherFactory::add('ControllerFactory');
- // Plugin syntax is also possible
- // Use options to set priority
- DispatcherFactory::add('Asset', ['priority' => 1]);
Dispatcher filters with higher priority
(lower numbers) - will be executedfirst. Priority defaults to 10
.
While using the string name is convenient, you can also pass instances intoadd()
:
When adding filters, you can control the order they are invoked in usingevent handler priorities. While filters can define a default priority using the$_priority
property, you can set a specific priority when attaching thefilter:
- DispatcherFactory::add('Asset', ['priority' => 1]);
- DispatcherFactory::add(new AssetFilter(['priority' => 1]));
The higher the priority the later this filter will be invoked.
Conditionally Applying Filters
If you don’t want to run a filter on every request, you can use conditions toonly apply it some of the time. You can apply conditions using the andwhen
options. The for
option lets you match on URL substrings, while thewhen
option allows you to run a callable:
The callable provided to when
should return true
when the filter should run.The callable can expect to get the current request and response as arguments.
- namespace App\Routing\Filter;
- use Cake\Event\Event;
- use Cake\Routing\DispatcherFilter;
- class TrackingCookieFilter extends DispatcherFilter
- {
- {
- $request = $event->getData('request');
- $response = $event->getData('response');
- if (!$request->getCookie('landing_page')) {
- $response->cookie([
- 'name' => 'landing_page',
- 'value' => $request->here(),
- 'expire' => '+ 1 year',
- ]);
- }
- }
- }
Save this file into src/Routing/Filter/TrackingCookieFilter.php. As you can see, like otherclasses in CakePHP, dispatcher filters have a few conventions:
- Class names end in
Filter
. - Generally filters extend
Cake\Routing\DispatcherFilter
.DispatcherFilter
exposes two methods that can be overridden in subclasses,they arebeforeDispatch()
and . These methods areexecuted before or after any controller is executed respectively. Both methodsreceive aCake\Event\Event
object containing theServerRequest
andResponse
objects ( andCake\Http\Response
instances) inside the$data
property.
While our filter was pretty simple, there are a few other interesting things wecan do in filter methods. By returning an Response
object, you canshort-circuit the dispatch process and prevent the controller from being called.When returning a response, you should also remember to call$event->stopPropagation()
so other filters are not called.
Note
When a beforeDispatch method returns a response, the controller, andafterDispatch event will not be invoked.
Let’s now create another filter for altering response headers in any publicpage, in our case it would be anything served from the PagesController
:
This filter will send a expiration header to 1 day in the future forall responses produced by the pages controller. You could of course do the samein the controller, this is just an example of what could be done with filters.For instance, instead of altering the response, you could cache it using and serve the response from the beforeDispatch()
callback.