Symfony Container Properties

Strange problem, I have a controller that uses \ Symfony \ Component \ DependencyInjection \ ContainerAwareTrait

class MainController { use \Symfony\Component\DependencyInjection\ContainerAwareTrait; /** * @Route("/", name="_index") * @Template() */ public function indexAction() { var_dump($this->container); return array(); } } 

but the result is NULL.

I tried:

  • Symfony 2.5. *
  • MAMP 3.0
  • PHP 5.4 5.5

My searches did not help me. I think the solution is easy.

Any ideas how to track this error?

UPD: When I expand from the controller, the container is accessible and everything works correctly. But according to symfony Controller, the link extension is optional, I can use traits instead.

+7
php traits containers symfony
source share
1 answer

I would venture to suggest, based on a quick look at the source code for Symfony: you still need to declare that you adhere to the ContainerAwareInterface interface.

Here's what the code looks like when Symfony installs the container on the controller.

 if ($controller instanceof ContainerAwareInterface) { $controller->setContainer($this->container); } 

So, I suppose you need to do something like this:

 use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; // ... class MainController implements ContainerAwareInterface { use ContainerAwareTrait; /** * @Route("/", name="_index") * @Template() */ public function indexAction() { var_dump($this->container); return array(); } 

}

As an aside, this is probably a pretty good example for Duck Typing , especially if they called the method something more specific or if it was cheaper to check the parameter types for methods at runtime

+20
source share

All Articles