簡體   English   中英

PHP (slim, php-di) 中的依賴注入

[英]Dependency injection in 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作為命名條目添加到容器中,您是否可以通過$container->get()LoggerInterface class 直接注入中間件? IE 在路由中routes.php App function:

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

簡而言之,我不認為您將能夠自動連接中間件的依賴關系,因為它們需要在附加到路由器之前構建。 您需要按照@Woodrow 的建議顯式注入依賴項,盡管我會選擇方法注入而不是 LoggerInterface 的構造函數注入,因為它會遵守 LoggerAwareInterface。

您可以讓依賴注入容器(PHP-DI)解析並將所有依賴注入到您的中間件中:

LoggerInterface::class => function (ContainerInterface $container) {
    return new Logger('name');
},

然后只需使用 class 名稱注冊中間件:

$app->add(\MiddleWare\MyAuthentication::class);

(您不應該將容器本身注入中間件)

就這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM