wto*_*rsi 7 php containers traits symfony
奇怪的问题,我有使用\ Symfony\Component\DependencyInjection\ContainerAwareTrait的控制器
class MainController
{
use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
/**
* @Route("/", name="_index")
* @Template()
*/
public function indexAction()
{
var_dump($this->container);
return array();
}
}
Run Code Online (Sandbox Code Playgroud)
但结果是NULL.
试穿:
我的搜索没有帮助我.我认为解决方案很简单.
任何想法如何追踪此错误?
UPD:当我从Controller扩展时,容器可用,一切正常.但根据symfony控制器参考扩展是可选的,我可以使用特征代替.
Chr*_*hey 20
我将根据对Symfony源代码的快速浏览进行猜测:您仍然需要声明您遵守ContainerAwareInterface接口.
每当Symfony在控制器上设置容器时,这就是代码的样子.
if ($controller instanceof ContainerAwareInterface) {
$controller->setContainer($this->container);
}
Run Code Online (Sandbox Code Playgroud)
那么我想你需要做这样的事情:
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();
}
Run Code Online (Sandbox Code Playgroud)
}
顺便说一下,对于Duck Typing来说,这可以说是一个非常好的例子,特别是如果他们将方法命名为更具体的一些,或者在运行时检查参数类型到方法是否更便宜