Middleware

Middleware is used in Tomahawk to make it easier to hook into the behaviour of services during a request.

Tomahawk includes middleware for Sessions, Cookies and String Responses.

You could create a middleware for checking if a user was logged in etc.

You add them in to the AppKernel, found in app/AppKernel.php

Creating your own Middleware

First create a class that extends Tomahawk\Middleware\Middleware.

The Middleware requires a boot method. Once you've done that you should have something that looks like:

When the middleware is booted, you have access to the Service container through $this->container.

Next you want to get the Event Dispatcher and listen on the Kernel Events. The following events are available:

  • KernelEvents::REQUEST - occurs at the very beginning of request dispatching.
  • KernelEvents::EXCEPTION - occurs when an uncaught exception appears.
  • KernelEvents::VIEW - event occurs when the return value of a controller is not a Response instance.
  • KernelEvents::CONTROLLER - occurs once a controller was found for handling a request.
  • KernelEvents::RESPONSE - occurs once a response was created for replying to a request.
  • KernelEvents::TERMINATE - occurs once a response was sent.
  • KernelEvents::FINISH_REQUEST - occurs when a response was generated for a request.

We'll use Tomahawk's Tomahawk\HttpCore\Middleware\StringResponse as an example.

This middleware listens on the KernelEvents::VIEW event and converts string responses returned from the controller to a Symfony Response.