activecollab/middlewarestack

Slim中间件栈实现的端口,作为一个独立的包

1.0.0 2016-11-10 13:10 UTC

This package is auto-updated.

Last update: 2024-09-05 01:24:21 UTC


README

Build Status

此包允许您构建一个中间件堆栈,并通过它们运行请求,直到它们相应的响应。堆栈是后进先出(LIFO),这意味着后来添加的中间件被认为是“外部”中间件,并且它们首先执行。

示例

$stack = new MiddlewareStack();

$stack->addMiddleware(function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) {
   // Route request to the contraoller, execute action, and encode action result to response

   if ($next) {
       $response = $next($request, $response);
   }
   
   return $response;
});

$stack->addMiddleware(function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) {
   if (!user_is_authenticated($request)) {
       return $response->withStatus(403); // Break here if user is not authenticated
   }

   if ($next) {
       $response = $next($request, $response);
   }
   
   return $response;
});

$request = new ServerRequest();
$response = $stack->process($request, new Response());

此示例展示了在请求被进一步发送到路由、控制器和结果编码之前进行的一个简单的授权检查。

错误处理

堆栈公开了一种处理异常(扩展\Exception类)和PHP错误(在PHP7及以上版本中为\Throwable,但不扩展\Exception类)的方式。

$stack->setExceptionHandler(function (Exception $e, ServerRequestInterface $request, ResponseInterface $response) {
    $response = $response->withStatus(500, 'Exception: ' . $e->getMessage());

    return $response;
});

$stack->setPhpErrorHandler(function (Throwable $e, ServerRequestInterface $request, ResponseInterface $response) {
    $response = $response->withStatus(500, 'PHP error: ' . $e->getMessage());

    return $response;
});

扩展点

您可以直接使用MiddlewareStack实现,也可以扩展它以改变其行为。有两个额外的protected方法,您可以使用它们在堆栈执行中挂钩自己的行为

  1. MiddlewareStack在执行过程中被调用,就像另一个中间件一样。如果需要在该处注入额外功能(例如,使用具有每个路由中间件堆栈的路由),则覆盖__invoke方法。
  2. finalizeProcessingprocess方法返回响应之前被调用。如果需要在返回响应之前对其进行某些操作,则覆盖它。

历史

我们在2016年11月发现的大多数中间件实现都假设并做了太多事情,它们本身就是微型框架 - 它们预计了路由、子堆栈等。

Slim框架有一个很好的中间件堆栈实现,但它不是一个独立的组件,这是我们需要的,所以我们决定将其提取出来。