Php Symfony 2服务容器为空
我是Symfony 2的新手,正在尝试创建一些简单的应用程序来学习。我创建了一个bundlePhp Symfony 2服务容器为空,php,symfony,Php,Symfony,我是Symfony 2的新手,正在尝试创建一些简单的应用程序来学习。我创建了一个bundleGoogleApiBundle。在捆绑包中,我有一个控制器YouTubeController,这是一项服务: //services.yml service: myname_googleapi_youtube: class: Myname\GoogleApiBundle\Controller\YouTubeController 在另一个bundle中,我尝试调用YouTubeCon
GoogleApiBundle
。在捆绑包中,我有一个控制器YouTubeController
,这是一项服务:
//services.yml
service:
myname_googleapi_youtube:
class: Myname\GoogleApiBundle\Controller\YouTubeController
在另一个bundle中,我尝试调用YouTubeController
//anotherController.php
$service = $this->get('myname_googleapi_youtube');
$result = $service->getResultFunction();
//YouTubeController.php
public function getResultFunction()
{
$parameter = $this->container->getParameter('a');
//...
}
然后我得到一个异常FatalErrorException:Error:调用非对象上的成员函数getParameter()。
,因为$this->container
为NULL
我搜索了一下,但没有得到答案。我做错了吗
//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);
}
}
谢谢。我得到了异常ServiceNotFoundException:service“myname\u googleapi\u youtube”依赖于一个不存在的服务“session\u container”。
这在Symfony看来确实很难看,因为基本控制器类实现了ContainerWareInterface。无论如何,好答案!如果类实现ContainerWareInterfaceServices,则需要设置容器:-类:Myname\GoogleapBundle\Controller\YouTubeControl调用:-[setContainer,[@service\u container]]