Using responsibility chain pattern to realize middleware function


In fact, middleware is nothing more than a filter. In the framework, requests or responses are filtered layer by layer. The most appropriate way to realize this function is the responsibility chain mode

The realization of responsibility chain mode can be seen in this essayResponsibility chain mode  

The following records how to implement the middleware in the framework

First of all, you need to define an abstract class of middleware. The abstract class should contain the next level node of the object, as well as a method to set the placement of the node and process the request

next_node = $next;

Then implement the specific middleware class


To achieve this, we need to instantiate each middleware and execute the class in turn

middlewares as $v){
                $pre_obj = new $v;
                $this->first_obj = $pre_obj;
                $next_obj = new $v;
                $pre_obj = $next_obj;

    public function dispatch(RequestInterface $request)


Here I define three middleware, and the running effect is as follows

[email protected]:/home/www/wwwroot/MySwoole# php index.php
string(13) "Before Middle"
string(11) "Next Middle"
string(12) "After Middle"


Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]