Middleware 中间件 - LzxHahaha/PandaPHP GitHub Wiki

基础用法

路由中可以定义任意个中间件,每个中间件接受一个Request类型和一个Response类型的参数。在中间件中使用Requestend函数可以终止此次请求。

Router::get('/hello/:word',
    function ($req, $res) {
        if (!is_null($req->params('word'))) {
            $req->end();
        }
    },
    function ($req, $res) {
        $res->send('hello' . $req->params('word'));
    }
);

传递参数

中间件中若是想传递值,需要将Request设为引用类型,并将值修改放入RequestmiddlewareData字段中。

Router::get('/hello/:name',
    function ($req, $res) {
        $name = $req->params('name');
        $req->middlewareData['isAdmin'] = $name === '小明';
    },
    function ($req, $res) {
        $isAdmin = $req->middlewareData['isAdmin'];
        if (!$isAdmin) {
            $req->end();
        }
    },
    function ($req, $res) {
        $res->send('hello' . $req->params('word'));
    }
);