我在src\trollmaster\TrollBundle\Services\DefaultService.php
namespace trollmaster\TrollBundle\DefaultService;
class DefaultService
{
protected $example;
protected function exampleFunction()
{
return null;
}
}
我的资源\ config \ services.yml:
services:
trollmaster.default_service:
class: trollmaster\TrollBundle\DefaultService
和命令php app/console container:debug
正确地返回了我的服务名称,但是当我想在Controller的构造中调用此服务时:
$this->DefaultService = $this->get("trollmaster.default_service");
我看到了这个错误:
Error: Call to a member function get() on a non-object
我做错了什么?
编辑:
当我想将控制器定义为服务
时/**
* @Route(service="DefaultController")
*/
class DefaultController
我收到了错误:
ClassNotFoundException: Attempted to load class "DefaultController" from namespace "trollmaster\TrollBundle
答案 0 :(得分:2)
原因是容器被注入到实现ContainerAwareInterface
...(即通过扩展Symfony\Bundle\FrameworkBundle\Controller\Controller
)......
...通过 setter-injection 。
TLDR:在构建对象之后执行setter-injection。
因此你无法做到......
$service = $this->get('service');
// ... or ...
$service = $this->container->('service');
...在__construct()
方法中,因为setContainer()
方法未被调用且$this->container
尚未设置。
您可以在 documentation 中详细了解不同类型的注射剂。
查看以下代码部分:
答案 1 :(得分:1)
这是因为构造函数不知道容器(如nifr解释的那样)。但你可以define your controller itself as a service。这是我猜的最好的做法,虽然我不知道你想要做什么。