0

基于https://github.com/DamienHarper/DoctrineAuditBundle我正在尝试为我的 Zend Expressive 应用程序开发审计模块。但我不知道如何在审计逻辑中获取用户数据(id)。

我看到这$user是作为请求属性传递的 vendor/zendframework/zend-expressive-authentication/src/AuthenticationMiddleware.php,但这并不能通过

$container->get(\Psr\Http\Message\ServerRequestInterface::class)->getAttribute(\Zend\Expressive\Authentication\UserInterface::class);
4

1 回答 1

2

您可能想再次阅读中间件的概念。简而言之,expressive 有一个中间件堆栈,根据请求,它通过特定的中间件层发送请求。

在您的示例中,请求通过 AuthenticationMiddleware。所以如果你有这个作为你的管道:

$app->pipe(AuthenticationMiddleware::class);
$app->pipe(AuditMiddleware::class);

请求首先通过 AuthenticationMiddleware,这使得 UserInterface 在请求中可用,然后通过 AuditMiddleware。

在您的 AuditMiddleware 和 AuthenticationMiddleware 之后的所有中间件中,您可以像这样访问 UserInterface:

function (ServerRequestInterface $request, RequestHandlerInterface $handler)
{
    $user = $request->getAttribute(UserInterface::class);

    // Do stuff here

    return $handler->handle($request);
}

因此,在您的情况下,您可能需要编写一个AuditMiddleware在 之后从请求中获取用户AuthenticationMiddleware并将其注入您的审核模块中。

于 2019-06-27T05:36:34.570 回答