Symfony container traits

走远了吗. 提交于 2020-01-02 02:56:05

问题


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



来源:https://stackoverflow.com/questions/25773823/symfony-container-traits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!