User Guides

Middleware

Middleware allows you to modify a request and its data at predefined stages of the request. From caching to authentication, middleware has many use cases that make it an incredibly powerful tool to have access to.


Stages

Each of the predefined stages that middleware can hook into can be used in a number of different ways, normally middleware will only hook into one or two stages of a request.

A list of the predefined stages can be found below, the stages are listed in order of execution, with security being executed first and end being executed last.

Stage Description
security This middleware should be used if the required function should be run before any state is altered or content is requested
init This middleware should be used if only the raw request and response are needed, for example caching
preData This middleware is called before the content defined in the vars section of the route is resolved, the request and response should still be in the state left by the init middleware
postData This middleware is called after the content defined in the vars section of the route is resolved, this middleware should run any sanity checks or mutations required on loaded content
preRender This middleare is called just before the page is rendered by the handling function, this might be a view or a controller depending on the routes configuration
postRender This middleware is run after the response is rendered and the intended content is final, this middleware is responsible for mutating the intended output, for example transforming array output or minifying HMTL output
end This middleware is run at the end of the request life cycle the state of request and response should be treated as finalised as the output has already been sent, this middleware should be used for caching and logging

Defining a Route

Before you can use a middleware, you must define a route that has a middleware key defining which middleware it needs to load. The middleware key of a route config accepts an array of middleware names, you can assign multiple middlewares to a single route and they will all be executed in the order that they were defined.

For example, the code below defines a route named account that is configured to use the userAuth middleware.

account:
  path: /account/
  middleware:
    - userAuth

Creating a Middleware

Middleware is located within the 'middleware' directory of your web directory. For our example, you will need to create a new file at middleware/userAuth.php, the contents of this file would like something like:

<?php

namespace Middleware;

class userAuth {

}

You would then create functions with the same name as the stage that you wanted to hook into, so for example if you wanted to hook into the security stage, you would do as follows:

<?php

namespace Middleware;

class userAuth {

  public function security($request, $response, $cms)
  {
    // Do something here...
  }

}