2013-10-29 49 views
0

我宣佈在service.yml一些相關服務,如:Symfony2 - LswMemcacheBundle - 我可以在另一個服務中使用memecache.default服務嗎?

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

回答

0

有沒有必要同時使用setter注入構造函數注入。

此外,您忘記了向構造函數添加第二個預期參數的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'); 
} 

instanciating新創建服務時,請確保你要麼它注入到其他服務,您想要使用它或從容器中獲取它。否則,memcache服務將不會被注入。例如:

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