如何将callable注入到Symfony2依赖注入容器服务中

3

给定以下类定义:

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;
    }
}

服务定义

<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>

感谢 Martin!

1
为什么它需要是可调用的?可能最好编写一个小类并注入它。 - Gerry
好的,这个类在供应商库中。将其包装在其他类中是一种解决方法,但我希望能够直接解决问题。感谢您的评论。 - iamtankist
有趣的东西,以前从没想过,但是canCache似乎是一个参数,而不是回调函数。这样做违反了单一职责原则。最好的方法可能是封装然后注入。 - Alexandru Olaru
我只是这个类的使用者,我相信签名会得到改进,只是发现问题本身很有趣。 - iamtankist
2个回答

3

尝试

<argument type="collection">
    <argument>ClassName::staticMethod</argument>
</argument>

或者

<argument type="collection">
    <argument type="service" id="serviceId" />
    <argument>instanceMethodName</argument>
</argument>

http://php.net/manual/de/language.types.callable.php


-1
也许可以创建一个依赖注入工厂,就像这个例子中所示:docs
它将返回您的可调用函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接