Dispatcher Filters

Deprecated since version 3.3.0: As of 3.3.0 Dispatcher Filters are deprecated. You should useMiddleware instead now.

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.

Built-in Filters

CakePHP comes with several dispatcher filters built-in. They handle commonfeatures that all applications are likely to need. The built-in filters are:

  • AssetFilter 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:
  1. // Use options to set cacheTime for your static assets
  2. // If not set, this defaults to +1 hour
  3. DispatcherFactory::add('Asset', ['cacheTime' => '+24 hours']);
  • 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 the Accept-Languageheader sent by the browser.

Using Filters

Filters are usually enabled in your application’s bootstrap.php file, butyou could load them any time before the request is dispatched. Addingand removing filters is done through Cake\Routing\DispatcherFactory. Bydefault, the CakePHP application template comes with a couple filter classesalready enabled for all requests; let’s take a look at how they are added:

  1. DispatcherFactory::add('Routing');
  2. DispatcherFactory::add('ControllerFactory');
  3.  
  4. // Plugin syntax is also possible
  5. DispatcherFactory::add('PluginName.DispatcherName');
  6.  
  7. // Use options to set priority
  8. 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():

  1. use Cake\Routing\Filter\RoutingFilter;
  2.  
  3. DispatcherFactory::add(new RoutingFilter());

Configuring Filter Order

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:

  1. DispatcherFactory::add('Asset', ['priority' => 1]);
  2. 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 for andwhen options. The for option lets you match on URL substrings, while thewhen option allows you to run a callable:

  1. // Only runs on requests starting with `/blog`
  2. DispatcherFactory::add('BlogHeader', ['for' => '/blog']);
  3.  
  4. // Only run on GET requests.
  5. DispatcherFactory::add('Cache', [
  6. 'when' => function ($request, $response) {
  7. return $request->is('get');
  8. }
  9. ]);

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.

Building a Filter

To create a filter, define a class in src/Routing/Filter. In this example,we’ll be making a filter that adds a tracking cookie for the first landingpage. First, create the file. Its contents should look like:

  1. namespace App\Routing\Filter;
  2.  
  3. use Cake\Event\Event;
  4. use Cake\Routing\DispatcherFilter;
  5.  
  6. class TrackingCookieFilter extends DispatcherFilter
  7. {
  8.  
  9. public function beforeDispatch(Event $event)
  10. {
  11. $request = $event->getData('request');
  12. $response = $event->getData('response');
  13. if (!$request->getCookie('landing_page')) {
  14. $response->cookie([
  15. 'name' => 'landing_page',
  16. 'value' => $request->here(),
  17. 'expire' => '+ 1 year',
  18. ]);
  19. }
  20. }
  21. }

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.
  • Classes are in the Routing\Filter namespace. For example,App\Routing\Filter.
  • Generally filters extend Cake\Routing\DispatcherFilter.
    DispatcherFilter exposes two methods that can be overridden in subclasses,they are beforeDispatch() and afterDispatch(). These methods areexecuted before or after any controller is executed respectively. Both methodsreceive a Cake\Event\Event object containing the ServerRequest andResponse objects (Cake\Http\ServerRequest 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:

  1. namespace App\Routing\Filter;
  2.  
  3. use Cake\Event\Event;
  4. use Cake\Routing\DispatcherFilter;
  5.  
  6. class HttpCacheFilter extends DispatcherFilter
  7. {
  8.  
  9. public function afterDispatch(Event $event)
  10. {
  11. $request = $event->getData('request');
  12. $response = $event->getData('response');
  13.  
  14. if ($response->statusCode() === 200) {
  15. $response->sharable(true);
  16. $response->expires(strtotime('+1 day'));
  17. }
  18. }
  19. }
  20.  
  21. // In our bootstrap.php
  22. DispatcherFactory::add('HttpCache', ['for' => '/pages'])

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 usingCake\Cache\Cache and serve the response from the beforeDispatch()callback.

While powerful, dispatcher filters have the potential to make your applicationmore difficult to maintain. Filters are an extremely powerful tool when usedwisely and adding response handlers for each URL in your app is not a good use forthem. Keep in mind that not everything needs to be a filter; Controllers andComponents are usually a more accurate choice for adding any request handlingcode to your app.