Symfony container traits

2019-04-25 10:12发布

问题:

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.

回答1:

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