Symfony 2 服务容器为空 [英] Symfony 2 service container is null
问题描述
我是 Symfony 2 的新手,正在尝试创建一些简单的应用程序来学习.我创建了一个包 GoogleApiBundle
.在捆绑包内,我有一个控制器 YouTubeController
,这是一项服务:
I am new to Symfony 2 and trying to create some simple application to learn. I created a bundle GoogleApiBundle
. Inside the bundle, I have a controller YouTubeController
, which is a service:
//services.yml
service:
myname_googleapi_youtube:
class: Myname\GoogleApiBundle\Controller\YouTubeController
在另一个包中,我尝试调用 YouTubeController
In another bundle, I try to call a function in YouTubeController
//anotherController.php
$service = $this->get('myname_googleapi_youtube');
$result = $service->getResultFunction();
//YouTubeController.php
public function getResultFunction()
{
$parameter = $this->container->getParameter('a');
//...
}
然后我得到一个异常 FatalErrorException: Error: Call to a member function getParameter() on a non-object ...
,因为 $this->container
是 NULL
.
Then I get an exception FatalErrorException: Error: Call to a member function getParameter() on a non-object ...
, because $this->container
is NULL
.
我搜索了但没有得到答案.我做错了吗?
I searched but didn't get an answer. Am I doing wrong?
推荐答案
//services.yml
service:
myname_googleapi_youtube:
class: Myname\GoogleApiBundle\Controller\YouTubeController
arguments: [@service_container]
你会:
<?php
namespace Myname\GoogleApiBundle\Controller
use Symfony\Component\DependencyInjection\ContainerInterface;
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);
}
}
<小时>
这种做法很有争议,因此我建议您快速阅读以下内容:
This practice is very controversial, so I'd recommend that you have a quick read at these:
这篇关于Symfony 2 服务容器为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!