Symfony container traits(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 容器特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony 容器特征


基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01