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 容器特征
基础教程推荐
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01