PHP中的依赖注入(Slim,php-di)

罗斯

我有一个Slim Php(slim4)应用程序,在该应用程序中添加了Monolog以便进行日志记录。我正在将记录器添加到应用程序中,如下所示:

$containerBuilder->addDefinitions([
  LoggerInterface::class => function (ContainerInterface $c) {
     $logger = new Logger('appname');
     ...
     return $logger

只需执行以下操作,就可以将记录器注入我的大多数课程中:

public function __construct(ContainerInterface $container = null, LoggerInterface $logger)
{
    // I can use $logger here

现在,我还想在身份验证之类的中间件中使用记录器。我看不到如何正确执行此操作。可以通过将记录器作为命名条目添加到容器中来使其工作,如下所示:

$containerBuilder->addDefinitions([
  "LoggerInterface" => function (ContainerInterface $c) {

然后通过从容器中将其作为构造函数参数传递给中间件:

$middlewares[] = new MyAuthentication(..., $container->get('LoggerInterface'));

但是这个:

  • a)按类名中断其他类的注入
  • b)显然不是最佳实践

那么,什么是将这个记录器注入中间件的正确方法呢?

伍德罗

无需LoggerInterface在容器中添加作为命名条目的,您是否可以LoggerInterface通过将该类直接注入到中间件中$container->get()IE中的routes.phpApp功能:

$container = $app->getContainer();
$app->add(new MiddleWare\MyAuthentication(..., $container->get(LoggerInterface::class)));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章