odan / slim4-skeleton

A Slim 4 Skeleton
https://odan.github.io/slim4-skeleton/
MIT License
439 stars 80 forks source link

How to use loggerFactory in Routing/JwtAuth #125

Closed mapicard closed 8 months ago

mapicard commented 8 months ago

I've implemented the LoggerFactory as described in your book and I'm using it successfully in various places. I've also implemented the JWT authentication as described but I'd like to add some logging in that class (Routing/JwtAuth). Using it as described on p84 by adding the LoggerFactory in the constructor, I end up with something like this

use App\Factory\LoggerFactory;
use Psr\Log\LoggerInterface; 
...
    public function __construct(Configuration $configuration
        , string $issuer
        , int $lifetime
        , LoggerFactory $loggerFactory
    ) {
        ...
    }

And this results in slim error

[23-Dec-2023 16:51:45 America/New_York] Slim Application Error
Type: ArgumentCountError
Code: 0
Message: Too few arguments to function App\Routing\JwtAuth::__construct(), 3 passed in /.../config/container.php on line 47 and exactly 4 expected

So I need to add this new parm on the call to this class in container.php... but how do I get a hold of the Logger instance of the App from there ???

    JwtAuth::class => function (ContainerInterface $container) {
        $configuration = $container->get(Configuration::class);
        $jwtSettings = $container->get('settings')['jwt']; 
        $issuer = (string)$jwtSettings['issuer']; 
        $lifetime = (int)$jwtSettings['lifetime'];
        return new JwtAuth($configuration, $issuer, $lifetime
                        //, $container->get(App::class)->get(LoggerFactory::class)
                        //, $app->getContainer()->get(\App\Factory\LoggerFactory::class)
                    ); 

Finally figured out to pass it as

$container->get(\App\Factory\LoggerFactory::class)