【问题标题】:Ho to Implement Slim like middleware mechanism如何实现类似 Slim 的中间件机制
【发布时间】:2017-03-10 14:25:49
【问题描述】:

我决定实现自己的小框架来实现依赖注入等东西。

现在我坚持我的中间件实现。我可以将中间件添加到路由中,但我想知道如何通过附加的中间件进行苗条循环。

我想以苗条的方式做到这一点,所以在每个中间件中我都可以返回请求或响应或下一个中间件。但是我如何对附加的中间件进行迭代。

这是我要继续的堆栈

class MiddlewareStack
{

    private $stack;

    public function addMiddleware(Middleware $middleware)
    {
        $this->stack[] = $middleware;
    }

    public function processMiddleware(Request $request, Response $response)
    {
    }
}

这就是中间件接口

public function __invoke(Request $request, Response $response, $next);

我想要

return $next($request,$response); 

在我的中间件类中,或者只是响应或请求。

这是在 slim 中创建可调用中间件的方法。

http://www.slimframework.com/docs/concepts/middleware.html#invokable-class-middleware-example

【问题讨论】:

    标签: php frameworks slim middleware


    【解决方案1】:

    Slim 3 首先将自己添加到堆栈中,即执行路由的Slim\App#__invoke()

    然后,当您添加中间件时,它会执行以下操作:(在此 slim 将可调用(匿名函数/可调用类)包装在 DeferredCallable 中之前,这有助于平等地执行函数和类(参见 Slim\App#add()) .

    protected function addMiddleware(callable $callable) // $callable is a DeferredCallable
    {
        $next = $this->stack->top(); // when it the first middleware this would be the route execution
        $this->stack[] = function (ServerRequestInterface $req, ResponseInterface $res) use ($callable, $next) {
            $result = call_user_func($callable, $req, $res, $next);
            return $result;
        };
    }
    

    (这只是简单代码,完整代码见:Slim\MiddlewareAwareTrait#addMiddleware()

    所以栈顶的中间件也会执行其他中间件,因为它是在 next 方法中提供的。

    那么当你要执行中间件时,获取栈顶的中间件并执行。

    $start = $this->stack->top();
    $resp = $start($req, $res);
    
    // $resp is now the final response.
    

    (见Slim\MiddlewareAwareTrait#callMiddlewareStack()

    【讨论】:

    • 嘿,感谢您编辑我糟糕的英语!我从 slim 复制了 miidleareAware Trait 以将我的中间件添加到堆栈中,但我遇到了和以前一样的问题......在这一行的中间件类中 $next($request,$response);带有需要第三个参数的消息
    • @SimonMüller 你确定吗,对我来说这一切都很好。
    • @SimonMüller 您是否使用匿名函数,如果是,您还需要使用DeferredCallable
    猜你喜欢
    • 2022-08-03
    • 2014-01-25
    • 2012-01-13
    • 2016-05-27
    • 2020-09-26
    • 2010-12-04
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多