我已经在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 ...
答案 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();