我是Symfony 2的新手,并尝试创建一些简单的应用程序来学习。我创建了一个包GoogleApiBundle
。在捆绑包内,我有一个控制器YouTubeController
,这是一个服务:
//services.yml
service:
myname_googleapi_youtube:
class: Myname\GoogleApiBundle\Controller\YouTubeController
在另一个包中,我尝试在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
。
我搜索但没有得到答案。我做错了吗?
答案 0 :(得分:5)
//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);
}
}
这种做法很有争议,所以我建议您快速阅读以下内容: