Reputation: 1058
I have registered my controller as a service so I can have my repository injected into my controller. This all seems to work fine, except that now when i try to return the view it bugs on returning data.
It gives an error and tries to load fos_rest.view_handler
:
Error: Call to a member function get() on a non-object
The get is being called in the symfony2 controller class on $this->container->get($id)
. For some reason the ContainerInterface
is not being injected in the ContainerAware
anymore when I use my controller as a service.
Has anyone experienced this problem before? How can I make sure the same container gets injected?
This is how I declared my class as a service:
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.users.apibundle.controller.user_controller" class="Acme\Users\ApiBundle\Controller\UserController">
<argument type="service" id="acme.users.user_repository"/>
</service>
</services>
</container>
And this is my controller:
class UserController extends FOSRestController
{
private $repository;
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
}
public function indexAction()
{
$users = $this->repository->findAll();
$view = $this->view($users, 200)
->setTemplate("MyBundle:Users:getUsers.html.twig")
->setTemplateVar('users');
return $this->handleView($view);
}
}
Upvotes: 2
Views: 257
Reputation: 17759
You need to inject the container into your controller using a call
so that it is available in the handleView
method.
Change your config to..
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.users.apibundle.controller.user_controller" class="Acme\Users\ApiBundle\Controller\UserController">
<argument type="service" id="acme.users.user_repository"/>
<!-- inject the container via the setContainer method -->
<call method="setContainer">
<argument type="service" id="service_container" />
</call>
</service>
</services>
Upvotes: 3