Symfony2 - LswMemcacheBundle - 我可以在其他服务中使用memecache.default服务吗?

时间:2013-10-29 15:26:13

标签: php symfony dependency-injection memcached

我已经在service.yml中声明了一些依赖的服务,例如:

content_helper:
    class:        Oilproject\ContentBundle\Helper\ContentHelper
    arguments:    ["@doctrine.orm.entity_manager", "@memcache.default"]
    calls:
                - [setMemcache, ["@memcache.default"]]

我的助手课程:

private $em;

    private $memcache;

    public function __construct(\Doctrine\ORM\EntityManager $em) {
        $this->em = $em;
        $this->memcache = $memcache;
    }

    public function setMemcache($memcache) {
        $this->memcache = $memcache;

        return $this;
    }
//...

但是当我打电话时

$memcache = $this->memcache;
$contents = $memcache->get($key);

此回归

Call to a member function get() on a non-object ... 

1 个答案:

答案 0 :(得分:0)

无需同时使用setter injection 构造函数注入。

此外,您忘记向构造函数添加memcache又名第二个预期参数。 使用当前的构造函数注入实现$this->memcache始终为null / a non-object,因为在创建对象/服务之后的异常状态。

试试这个:

<强>配置:

content_helper:
    class:        Vendor\Your\Service\TheClass
    arguments:    ["@doctrine.orm.entity_manager", "@memcache.default"]

<强>类

private $em;
private $memcache;

public function __construct(\Doctrine\ORM\EntityManager $em, $memcache) {
    $this->em = $em;
    $this->memcache = $memcache;
}

// example usage
public function someFunction()
{
    return $this->memcache->get('key');
}

确保在实现新创建的服务时,将其注入要使用它的其他服务或从容器中获取。否则将不会注入memcache服务。例如:

 // getting i.e. inside a controller with access to the container
 $value = $this->container->get('content_helper')->someFunction();