How to Create Middleware in Slim with Closure and Class

What Will I Learn?

  • Create Middleware with Closure
  • Create Middleware with Class

Requirements

  • Basic Intermediate PHP OOP
  • Localhost Xampp, Wampp, or etc
  • Install Slim
  • Basic Slim

Difficulty

  • Intermediate

Preparation

Before following this tutorial. I suggest you watch some of the other Slim tutorials. Especially in the Slim MVC section. Because I will use the Structure MVC in this tutorial. Slim is a microframework, so when fresh install slim does not have MVC and Middleware system like other PHP Framework.

Create Middleware System

Slim does not come with the power of any other PHP framework that is Middleware System. We will make it in this tutorial.

What is Middleware?

Middleware is the way we protect certain parts or specific routing on our website. We will not be granted access before we go through the Middleware. so Middleware is a filter before the user goes into a particular routing or part.

There are three main parameters on the middleware:

  • $request: request is an input or request received.
  • $response: response is a response that we will do after getting an input or request.
  • $next: next means the response that we continue if the response is successful.

There are two ways to create a middleware:

  • Closure
  • Class

Make Middleware with Closure

If we make middleware by the closure. We have to create a function that is stored in the variable and the variable will be used each we want to use middleware. We will declare middleware with a closure like this.

Example:


$mw = function($request,$response,$next){
    // Before Middleware
    // Response Middleware
    // After Middleware
}

  • $mw: I created a variable for storing middleware functions. So we can use middleware function by accessing variable $mw.
  • function($request,$response,$next): I have described above the middleware function has 3 mandatory parameters. those are $request,$response,$next.

in the middleware we can determine 3 stages:

  • 1. Before Middleware: We can run a function or anything before the middleware.
  • 2. Response Middleware: After we passed before middleware. we can continue Response.
  • 3. After Middleware: We can not only run something before the response, we can also do something after the response.

Implement the code:

We can make an example to see how the middleware works. I have created a routing. which we will give middleware function. how to use the add() function. add() has one parameter that contains the middleware function that we have saved in the $mw.


$mw = function($request,$response,$next){
    // Before Middleware
    $response->getBody()->write("Before Middleware");
    // Response Middleware
    $response = $next($request, $response);
    // After Middleware
    $response->getBody()->write("After Middleware");
    return $response;
}
$app->get('/', 'App\controllers\forumController:index')->add($mw);

  • $response->getBody()->write("Before Middleware");: by using the $response that has been parameter we can give the output of the middleware function. and for example I just write('Before Middleware') to make sure we can run something before giving response.

  • $response = $next($request, $response);: To continue our response. We use $next() . $next() needs two parameters: $request and $response. and then we can we save in a variable to return.

  • return $response;: We return the $ response variable containing $next($request, $response)

  • $app->get('/', 'App\controllers\forumController:index')->add($mw);: This is the routing system that I have created in the previous tutorial. for more detail please see section routing-slim. We use the functionality provided by SLIM to add middleware. Its function is add(). We can pass the variable that contains the function of the middleware we have created, like this add($mw).

We can see the result by running xampp and open your browser.

Screenshot_36.png

Make Middleware with Class

The second way to create middleware by creating a class that serves as a middleware.

  • Create Class
    We will create a class with the name of authMiddlewareClass. This is just a class name, you can replace it with what you want. In this function, we will use the __invoke method.

What is the __invoke method?

The __invoke method has uses like __construct, but __invoke run when we call its class name as a function.

The example we use its class like this:

new authenticationClass(), by using its function like this, we call __invoke automatically.

Example The Class Middleware:


<?php
class authMiddlewareClass{
    public function __invoke($request, $response, $next){
            // Before Middleware
            $response->getBody()->write("Before Middleware");
            // Response Middleware
            $response = $next($request, $response);
            // After Middleware
            $response->getBody()->write("After Middleware");
            return $response;
    }
}

  • public function __invoke($request, $response, $next): Because this __invoke function to run the middleware we need to give 3 mandatory parameters that is $request , $response and $next.

Not much different middleware concept with closure and with class. The most fundamental difference lies in the use of __invoke methods and middleware functions that we write in a function so that the code becomes more neat. the following is how to implement in the routing system.

Implement function in Routing:


$app->get('/', 'App\controllers\forumController:index')
    ->add(new authMiddleware());

  • ->add(new authMiddleware());: We can use that class with the add() method of Slim. and make the function name as a parameter.

Difference Between Closure and Class usage

  • Closure

$app->get('/', 'App\controllers\forumController:index')->add($mw);
In closure we use the variable parameter $mw which contains the function of the middleware.

  • Class

$app->get('/', 'App\controllers\forumController:index')->add(new authMiddleware())
If using a class we have to create a class first and need __invoke method to automate the middleware functionality.

We have finished making the concept of middleware in slim. thanks for following this tutorial .

Curiculm Slim



Posted on Utopian.io - Rewarding Open Source Contributors

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center