php – Symfony 2服务容器为空
发布时间:2020-12-13 17:26:17 所属栏目:PHP教程 来源:网络整理
导读:我是Symfony 2的新手,并试图创建一些简单的应用程序来学习.我创建了一个捆绑GoogleApiBundle.在捆绑包内,我有一个控制器YouTubeController,这是一项服务: //services.ymlservice: myname_googleapi_youtube: class: MynameGoogleApiBundleControllerYouT
我是Symfony 2的新手,并试图创建一些简单的应用程序来学习.我创建了一个捆绑GoogleApiBundle.在捆绑包内,我有一个控制器YouTubeController,这是一项服务:
//services.yml service: myname_googleapi_youtube: class: MynameGoogleApiBundleControllerYouTubeController 在另一个包中,我尝试在YouTubeController中调用一个函数 //anotherController.php $service = $this->get('myname_googleapi_youtube'); $result = $service->getResultFunction(); //YouTubeController.php public function getResultFunction() { $parameter = $this->container->getParameter('a'); //... } 然后我得到一个异常FatalErrorException:错误:在非对象上调用成员函数getParameter(),因为$this->容器是NULL. 我搜索但没有得到答案.我做错了吗? 解决方法//services.yml service: myname_googleapi_youtube: class: MynameGoogleApiBundleControllerYouTubeController arguments: [@service_container] 你会有: <?php namespace MynameGoogleApiBundleController use SymfonyComponentDependencyInjectionContainerInterface; class YouTubeController { /** * @param ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * Obtain some results */ public function getResultFunction() { $parameter = $this->container->getParameter('a'); //... } /** * Get a service from the container * * @param string The service to get */ protected function get($service) { return $this->container->get($service); } } 这种做法很有争议,所以我建议您快速阅读以下内容: > Controllers as Services in Symfony2 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |