Symfony container traits
I'll venture a guess based on a quick glance into the Symfony source code: You still need to declare that you adhere to the ContainerAwareInterface
Interface.
This is what the code looks like whenever Symfony is setting a container on a controller.
if ($controller instanceof ContainerAwareInterface) {
$controller->setContainer($this->container);
}
So then 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 arguably a pretty good case for Duck Typing, particularly if they had named the method something a bit more specific or if it were cheaper to inspect the parameter types to methods at runtime
![wtorsi](https://i.stack.imgur.com/ThIx5.jpg?s=256&g=1)
wtorsi
Hi 😏 I'm a full stack website developer, a founder of «It's done». We are creating "lean", cool and fast 😎 websites based on Symfony.
Updated on June 12, 2022Comments
-
wtorsi about 2 years
Strange problem, I have controller which 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 result is NULL.
Tried on:
- Symfony 2.5.*
- MAMP 3.0
- PHP 5.4 5.5
My searches have not helped me. I think the solution is easy.
Any ideas how to trace this error?
UPD: When i extend from Controller, container is available and everything is working properly. But according to symfony Controller reference extending is optional, i can use traits instead.