Middleware API

Last updated on
27 May 2022

This documentation needs work. See "Help improve this page" in the sidebar.

Drupal 8/9 has a Middleware API that it adopted from the broader PHP community: https://github.com/stackphp. This one-liner from their project page captures it well:

Symfony's HttpKernelInterface provides a solid interface, which makes creating and sharing framework-agnostic HTTP filters a breeze!

So, StackPHP:

  1. builds on top of Symfony's HttpKernelInterface
  2. is a convention for composing HttpKernelInterface middlewares.

That's it!

Dependency Injection

The Drupal\Core\DependencyInjection\Compiler\StackedKernelPass compiler pass implicitly prepends the inner kernel as first constructor argument of the middleware. Thus, you do not need to define arguments in your modules *.services.yml definition for the middleware unless your middleware depends on another registered service.

Examples

You can find lots of examples at https://github.com/stackphp/stackphp.com/blob/master/source/middlewares.....

Drupal core

In Drupal core, the following concepts are implemented via StackPHP middlewares:

  1. Internal page cache ( \Drupal\page_cache\StackMiddleware\PageCache)
  2. content negotiation (\Drupal\Core\StackMiddleware\NegotiationMiddleware)
  3. reverse proxy support (\Drupal\Core\StackMiddleware\ReverseProxyMiddleware)
  4. session handling (\Drupal\Core\StackMiddleware\Session)

Drupal Contributed Modules

  1. Rate Limiting Service for API consumption (https://www.drupal.org/project/rate_limiter)

3rd Party Github Hosted

  1. CORS-Drupal8 (https://github.com/dmouse/cors-drupal8)

Caution

Middlewares run on every request. Effectively, the Middleware API is the equivalent of Drupal 7's hook_boot(). So, make sure they run at the appropriate time (i.e. the appropriate order), and ensure they do as little I/O as possible. Because every request will be impacted. Add one slow StackPHP middleware, and the entire Drupal 8 site will be slow!

See also

Tags

Help improve this page

Page status: Needs work

You can: