奇怪的问题, 我有使用 \Symfony\Component\DependencyInjection\ContainerAwareTrait
的 Controllerclass 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/