Skip to content

Middleware

Middleware is generally used to intercept requests or responses. For example, it can uniformly verify the user's identity before executing a controller and redirect the user to the login page if they are not logged in. It can also be used to record interface request logs, etc.

Running Logic

A middleware can include two methods, before() and after(). The before() method is executed when the controller is initialized, and the after() method is executed after the controller responds.

Note

The code in after() is executed after the controller uses $this->success(), $this->error(), $this->rawOutput() for responses and before $this->redirect() is used for redirection.

Middleware Configuration

Middleware is configured in the config/middleware.php file, as shown below:

php
<?php

return [
    //    '' => [
    //        // Global middleware
    //        'AccessControl',
    //    ],
    '/admin' => [
        "admin",
    ],
    '/merchant/test' => [
        "admin",
    ],
];

Each array item represents a route prefix and the corresponding list of middleware to be executed.

A URI route can be configured with multiple middleware. The middleware's before() methods are executed in the order of configuration, and the after() methods are executed in reverse order.

Middleware Writing

Each middleware should be placed in the app/middleware directory. The file name, class name, and the name in the configuration file should be consistent. The class's namespace should be app\middleware, and the class should include public before() or after() methods.

An example of a middleware:

php
<?php

namespace app\middleware;

use framework\support\Redis;
use framework\support\Request;

class admin
{
    function before()
    {

        $request = request();
        $authHeader = $request->header("Authorization");
        $token = null;
        if ($authHeader) {
            $arr = explode(' ', $authHeader);
            if (count($arr) > 1) {
                $token = $arr[1];
            } else {
                $token = $authHeader;
            }
        }
        $isExistToken = Redis::get("admin_" . $token);
        if (!$isExistToken) {
            Response::Error(401, "令牌过期");
            return false;
        }
    }

    function after()
    {
        // Record administrator operation logs;
    }
}

Return Values of Middleware

If the before() method of a middleware returns false, subsequent middleware and the controller will not be executed, and an error response will be returned directly.