Search code examples
phpdoctrinemezzio

How to get User object in Doctrine event subscriber in Zend Expressive


Based on https://github.com/DamienHarper/DoctrineAuditBundle I'm trying to develop audit module for my Zend Expressive application. But I don't know how to get the User data (id) within audit logic.

I see that $user is passed as request attribute in vendor/zendframework/zend-expressive-authentication/src/AuthenticationMiddleware.php, but this doesn't make it available via

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

Solution

  • You might want to read again about the concept of middleware. In short, expressive has a middleware stack and depending on a request, it sends a the request through specific layers of middleware.

    In your example the request goes through AuthenticationMiddleware. So if you have this as your pipeline:

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

    The request goes first through the AuthenticationMiddleware, which makes the UserInterface available in the request, and next through the AuditMiddleware.

    In your AuditMiddleware and all middlewares after the AuthenticationMiddleware you can access the UserInterface like this:

    function (ServerRequestInterface $request, RequestHandlerInterface $handler)
    {
        $user = $request->getAttribute(UserInterface::class);
    
        // Do stuff here
    
        return $handler->handle($request);
    }
    

    So in your case you probably need to write an AuditMiddleware that grabs the user from the request after the AuthenticationMiddleware and injects it in your Audit module.