Symfony 如何将callable注入Symfon2依赖项注入容器服务
给定以下类定义Symfony 如何将callable注入Symfon2依赖项注入容器服务,symfony,dependency-injection,guzzle,Symfony,Dependency Injection,Guzzle,给定以下类定义 class CacheSubscriber implements SubscriberInterface { public function __construct( CacheStorageInterface $cache, callable $canCache ) { $this->storage = $cache; $this->canCache = $canCache; }
class CacheSubscriber implements SubscriberInterface
{
public function __construct(
CacheStorageInterface $cache,
callable $canCache
) {
$this->storage = $cache;
$this->canCache = $canCache;
}
我想将此类定义为Symfony2 DIC中的服务
而对于第一个论点,我们相对清楚地知道该怎么做
<service id="nsp_generic.guzzle.subscriber.cache" class="GuzzleHttp\Subscriber\Cache\CacheSubscriber">
<argument type="service" id="nsp_generic.redis.cache"/>
<!-- ??? -->
</service>
如何定义和注入第二个参数
更新
用户meckhardt将此推到了正确的方向
助手类
<?php
namespace Nsp\GenericBundle\Service\Cache;
class CacheConfig {
public static function canCache() {
return true;
}
}
试试看
可以创建一个依赖项注入工厂,如本例所示:
它将返回您的可调用项。为什么它需要是可调用项?最好是围绕它编写一个小类并注入它。好吧,这个类在供应商库中。将其包装在其他类中是一种变通方法,希望直接解决问题。谢谢你的评论。有趣的东西从来没有想过,但是canCache
似乎是一个参数,而且不是回调,你这样做有点违反了单一责任原则。是的,也许最好的办法是包装它,然后注入。我只是这个类的消费者,我相信签名会改进,只是发现问题本身很有趣。
<service id="nsp_generic.guzzle.subscriber.cache" class="GuzzleHttp\Subscriber\Cache\CacheSubscriber">
<argument type="service" id="nsp_generic.guzzle.subscriber.cache.storage"/>
<argument type="collection">
<argument>Nsp\GenericBundle\Service\Cache\CacheConfig</argument>
<argument>canCache</argument>
</argument>
</service>
<argument type="collection">
<argument>ClassName::staticMethod</argument>
</argument>
<argument type="collection">
<argument type="service" id="serviceId" />
<argument>instanceMethodName</argument>
</argument>