Middleware API
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:
- builds on top of Symfony's
HttpKernelInterface
- 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:
- Internal page cache (
\Drupal\page_cache\StackMiddleware\PageCache)
- content negotiation (
\Drupal\Core\StackMiddleware\NegotiationMiddleware
) - reverse proxy support (
\Drupal\Core\StackMiddleware\ReverseProxyMiddleware
) - session handling (
\Drupal\Core\StackMiddleware\Session
)
Drupal Contributed Modules
- Rate Limiting Service for API consumption (https://www.drupal.org/project/rate_limiter)
3rd Party Github Hosted
- 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
- https://github.com/stackphp
- core committer concern: https://www.drupal.org/node/1869548#comment-11287753
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion