【问题标题】:How is possible to execute a piece of code when an object is created in PHP-DI?在 PHP-DI 中创建对象时,如何执行一段代码?
【发布时间】:2019-09-18 07:54:29
【问题描述】:

我像这样使用\DI\Container 设置我的依赖项:

$this->container = new \DI\Container();
$this->container->set('AdyenClient', \DI\create('\Adyen\Client'));
$this->container->set('AdyenCheckout', \DI\create('\Adyen\Service\Checkout')->constructor($this->container->get('AdyenClient')));

\Adyen\Client 不能在构造中配置,所以我需要在第一次创建后执行一个与创建的对象没有任何关联的configClient() 函数。

是否可以在$this->container->get('AdyenClient') 第一次创建对象时“触发”该方法或任何其他代码,即使需要更改依赖项的设置方式?

据我阅读,官方文档中没有任何类似的场景。

【问题讨论】:

    标签: php dependency-injection constructor callback php-di


    【解决方案1】:

    使用 DI\create()

    您可以使用CreateDefinitionHelper::method 来定义创建对象时的方法调用。像这样:

    $this->container = new \DI\Container();
    $this->container->set('AdyenClient',
      \DI\create('\Adyen\Client')->method('configClient', $param1, $param2));
    $this->container->set('AdyenCheckout',
      \DI\create('\Adyen\Service\Checkout')->constructor($this->container->get('AdyenClient')));
    

    PHP-DI 将在首次创建后使用 $param1 和 $param2 调用 AdyenClient::configClient。

    使用 DI\factory()

    或者,您可以使用DI\factory 函数(从回调中创建FactoryDefinitionHelper):

    $this->container = new \DI\Container();
    $this->container->set('AdyenClient',
      \DI\factory(function (Psr\Container\ContainerInterface $container) {
        $adyenClient = $container->get('\Adyen\Client');
        configClient($adyenClient);
        return $adyenClient;
      });
    $this->container->set('AdyenCheckout',
      \DI\create('\Adyen\Service\Checkout')->constructor($this->container->get('AdyenClient')));
    

    这应该是一种更灵活的方式来定义容器中的任何延迟加载的东西。

    【讨论】:

    • 嗨@Koala Yeung。感谢您的回答,但是 configClient 类中不存在 AdyenClient 类中的方法,我也不能用它扩展它,因为它不是我写的。我需要能够调用与创建的对象没有直接关联的任何其他代码。
    • 最后我通过链接AdyenClient对象中可用的所有配置方法来做到这一点。
    • @KristosAthanasiadis:为答案添加了另一种方法。它应该更灵活。
    • 尽管,我是按照你的第一个例子做的,它产生了一些丑陋的[难以阅读]代码——因为在那个特定的类中有几个配置方法,第二种方法是真正的我从一开始就需要。通常,\DI\Factory 方法是首选方法,当 -- 就我而言,所创建对象的配置不限于一种方法。不过感谢您的努力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多