1

我在我的 PHP 项目中使用 PHP-DI 6 容器。在我的程序开始时,我只是初始化容器并获取Application注入所有依赖项的类。

    $container   = new Container();
    $application = $container->get(Application::class);

    $application->initialize();
    $application->run();

在下图中,您可以看到我在项目中使用的类。

类图

Asterisk Dispatcher 被注入到 Application 类中。

private $asteriskDispatcher;

public function __construct(AsteriskDispatcher $asteriskDispatcher)
{
    $this->asteriskDispatcher = $asteriskDispatcher;
}

然后,在AsteriskDispatcher类中,我需要创建一个 Asterisk Manager 实例列表,该列表在不久的将来也将包含一些依赖项。

我不想通过所有类继承容器。有没有办法将 PHP-DI 容器初始化为单例,所以我可以随时使用它来创建一些对象?

这就是我现在这样做的方式,我只是在我的AsteriskDispatcher类中创建了一个新的 PHP-DI 容器实例,这看起来太糟糕了。

class AsteriskDispatcher implements AsteriskDispatcherInterface
{
    private $listOfAsteriskManagers;

    public function __construct()
    {
        $configurations = AsteriskConnectionsConfiguration::$connectionsConfiguration;

        $this->listOfAsteriskManagers = new \SplDoublyLinkedList();

        $container = new Container();

        foreach ($configurations as $configuration)
        {
            $this->listOfAsteriskManagers->push($container->make(AsteriskManager::class,
                array('configuration' => $configuration)));
        }
    }
}

我真的很想了解如何在不违反 SOLID 原则的情况下使用 PHP-DI 容器。

4

1 回答 1

2

文档中:

如果您需要在服务、控制器或其他任何内容中使用 make() 方法,建议您针对 FactoryInterface * 进行类型提示。这样可以避免将您的代码耦合到容器。DI\FactoryInterface 会自动绑定到 DI\Container,因此您无需任何配置即可注入它。

*强调我的

因此,您应该将AsteriskDispatcher构造函数更改为:

public function __construct(FactoryInterface $factory) {
  // your code ...
  // more of your code ...

  $factory->make(AsteriskManager::class, ['configuration' => $configuration]);

  // the rest of your code.

}

PS:单身 人士是 邪恶的(大部分)。

于 2019-01-14T08:38:16.957 回答