Symfony 容器特征 [英] Symfony container traits

查看:24
本文介绍了Symfony 容器特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪的问题,我有使用 SymfonyComponentDependencyInjectionContainerAwareTrait

Strange problem, I have controller which uses SymfonyComponentDependencyInjectionContainerAwareTrait

class MainController
{
    use SymfonyComponentDependencyInjectionContainerAwareTrait;
    /**
     * @Route("/", name="_index")
     * @Template()
     */
    public function indexAction()
    {
         var_dump($this->container);

         return array();
    }
}

但结果为 NULL.

试穿:

  • 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: 当我从 Controller 扩展时,容器可用并且一切正常.但是根据 symfony 控制器的参考扩展是可选的,我可以使用特征来代替.

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.

推荐答案

我会根据对 Symfony 源代码的快速浏览来冒险猜测:您仍然需要声明您遵守 ContainerAwareInterface 接口.

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.

这就是 Symfony 在控制器上设置容器时代码的样子.

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 SymfonyComponentDependencyInjectionContainerAwareInterface;
use SymfonyComponentDependencyInjectionContainerAwareTrait;
// ...
class MainController implements ContainerAwareInterface 
{
    use ContainerAwareTrait;
    /**
     * @Route("/", name="_index")
     * @Template()
     */
    public function indexAction()
    {
         var_dump($this->container);

         return array();
    }

}

顺便说一句,这可以说是 Duck Typing 的一个很好的案例,特别是如果他们已将方法命名为更具体的名称,或者在运行时检查方法的参数类型是否更便宜

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

这篇关于Symfony 容器特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆