php - Symfony 容器特性

标签 php symfony containers traits

奇怪的问题, 我有使用 \Symfony\Component\DependencyInjection\ContainerAwareTrait

的 Controller
class MainController
{
    use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
    /**
     * @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

我的搜索没有帮助我。我认为解决方案很简单。

有什么想法可以追踪这个错误吗?

UPD:当我从 Controller 扩展时,容器可用并且一切正常。但根据 symfony Controller 引用,扩展是可选的,我可以改用 traits。

最佳答案

我将根据对 Symfony 源代码的快速浏览进行大胆猜测:您仍然需要声明您遵守 ContainerAwareInterface 接口(interface)。

这就是 Symfony 在 Controller 上设置容器时代码的样子。

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

那么我想你需要做这样的事情:

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();
    }

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

关于php - Symfony 容器特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25773823/

相关文章:

php - 多个 if 语句有效,除非值为 null

php - 如何在没有交互的情况下运行doctrine 2 迁移命令行?

php - KNP Doctrine 行为与 Atlantic18 Doctrine 扩展

symfony - 如何在我的选择选项中禁用编码 "&"

php - Doctrine 连接表没有反射(reflect)

html - 表格 'width' css属性不能防止表格属性超出其容器的宽度

C++ 设计容器和管理列表返回

javascript - 根据下拉响应更新div而不刷新

php - 如何使用动态数据和谷歌图表?

html - 在相对定位的 div 的 100% 宽度内垂直和水平居中 div