问题描述
我决定实施自己的小型框架来实施诸如依赖注入之类的东西.
I decided to implement my own small framework to implement such stuff like dependency injection etc.
现在,我坚持使用中间件实现.我可以将中间件添加到路由中,但我想知道附加的中间件如何通过苗条的循环.
Now I'm stucking at my middleware implementation. I can add middleware to a route but I im wondering how slim loops through the attached middleware.
我想做一个苗条的方法,所以在每个中间件中,我都可以返回一个请求或响应或下一个中间件.但是我怎么也可以遍历我所连接的中间件.
I'd like to do it the slim way, so in every middleware I can return a request or a response or the next middleware. But how do I have too iterate over my attached middleware.
这是我要继续的堆栈
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);
在我的中间件类中,或者只是响应或请求.
in my middleware classes or just a response or a request.
以下是创建可苗条调用的中间件的方法.
Here's how to create middlware callable in slim.
http://www.slimframework.com/docs/concepts/middleware.html#invokable-class-middleware-example
推荐答案
Slim 3首先将自身添加到 Slim\App#__invoke()
,它将执行路由.
Slim 3 first adds itself to the stack which is the Slim\App#__invoke()
which executes the route.
然后,当您添加中间件时,它会执行以下操作:(在此苗条包装可调用的(匿名函数/可调用类)之前,它位于 DeferredCallable
有助于平等地执行函数和类(请参见 Slim\App#add()
).
Then, when you add a middleware it does the following: (before this slim wrapps the callable (annonymous function/invokable class) inside a DeferredCallable
which helps to execute both the function and class equally (See 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()
)
(This is only the simple code, for full code see: Slim\MiddlewareAwareTrait#addMiddleware()
)
因此,位于堆栈顶部的中间件也将执行其他中间件,因为它是在下一个方法中提供的.
So the middleware which is on top of the stack executes the other middleware as well, because it is provided in the next method.
然后,当您要执行中间件时,获取位于堆栈顶部的中间件并执行它.
Then when you want to execute the middleware, get the middleware which is on top of the stack and execute it.
$start = $this->stack->top();
$resp = $start($req, $res);
// $resp is now the final response.
(请参见 Slim\MiddlewareAwareTrait#callMiddlewareStack()
)
(see Slim\MiddlewareAwareTrait#callMiddlewareStack()
)
这篇关于如何实现类似中间件机制的Slim的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!