将依赖注入容器传递给静态方法 [英] Pass Dependency Injection Container to static method

查看:39
本文介绍了将依赖注入容器传递给静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些传统课程.许多类是使用工厂类实例化的.

I have some Legacy classes. Many classes are instantiated using a Factory Class.

还有一个单例类.

将来我想用 DIC 完全替换它们.目前,代码库很大,无法做到这一点.

In the future I want to replace them completely with the DIC. For the moment the codebase is to large to do this.

现在我的目标是将 DI-Container 注入到由 Singleton 类实例化的每个服务中.Singleton 类有一个带有此签名的静态方法.

Now my goal is to inject the DI-Container into every Service instantiated by the Singleton class. The Singleton class has a static method with this signature.

final class Singleton
{
  private static $singletonCache = array();

  public static function getInstance($namespace, $className)
  {
  }
}

在这个函数里面我想检查:

inside of this function I want to check for:

$instance = new $className();

if($instance instanceof ContainerAwareInterface)
{
  // TODO: how do we get the container here
  $instance->setContainer($container);
}

但是我怎样才能最好地将容器放入我的单例类"中,它只被静态调用?

But how can I best get the container inside of my "singleton class", which is only called statically?

推荐答案

在引导代码早期的某个地方,但是在实例化容器之后,您可以将容器传递给您的单例类:

Somewhere early in your bootstrapping code, but after the container is instantiated, you can pass the container to your singleton class:

Singleton::setContainer($container);

它将容器存储在一个静态属性中:

It would store the container in a static property:

final class Singleton
{
    // ...

    private static $container;

    public static function setContainer(ContainerInterface $container)
    {
        self::$container = $container;
    }
}

然而,正如您在单例类示例中了解到的那样,所有全局状态都让您头疼.传递容器(并使用 ContainerAware)是需要避免的.通过将容器传递给您的服务,您使它们依赖于整个服务世界.仅通过您实际需要的合作者更干净.测试也容易得多.

However, as you learned on the example of your singleton class, all global state gives you is headaches. Passing the container around (and using ContainerAware) is something to avoid. By passing the container to your services you're making them rely on the whole world of services. It's cleaner to only pass collaborator you actually need. It's also far easier to test.

这篇关于将依赖注入容器传递给静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆