如何将 callable 注入 Symfon2 依赖注入容器服务

How can I inject callable into Symfon2 Dependency Injection Container service

给定以下 class 定义

class CacheSubscriber implements SubscriberInterface
{
    public function __construct(
        CacheStorageInterface $cache,
        callable $canCache
    ) {
        $this->storage = $cache;
        $this->canCache = $canCache;
    }

我想将此 class 定义为 Symfony2 DIC 中的一项服务。

虽然相对清楚如何处理第一个参数

<service id="nsp_generic.guzzle.subscriber.cache" class="GuzzleHttp\Subscriber\Cache\CacheSubscriber">
    <argument type="service" id="nsp_generic.redis.cache"/>
    <!-- ??? -->
</service>

如何定义和注入第二个参数?

更新

用户 meckhardt 将其推向了正确的方向。

帮手class

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

谢谢马丁!

尝试

<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

也许像这个例子一样创建一个依赖注入工厂:docs
这将 return 您的可调用对象。