我是Symfony 2的新手,并试图创建一些简单的应用程序来学习.我创建了一个包GoogleApiBundle.在捆绑包内,我有一个控制器YouTubeController,这是一个服务:
//services.yml
service:
myname_googleapi_youtube:
class: Myname\GoogleApiBundle\Controller\YouTubeController
Run Code Online (Sandbox Code Playgroud)
在另一个包中,我尝试调用函数 YouTubeController
//anotherController.php
$service = $this->get('myname_googleapi_youtube');
$result = $service->getResultFunction();
//YouTubeController.php
public function getResultFunction()
{
$parameter = $this->container->getParameter('a');
//...
}
Run Code Online (Sandbox Code Playgroud)
然后我得到一个例外FatalErrorException: Error: Call to a member function getParameter() on a non-object ...,因为$this->container是NULL.
我搜索但没有得到答案.我做错了吗?
//services.yml
service:
myname_googleapi_youtube:
class: Myname\GoogleApiBundle\Controller\YouTubeController
arguments: [@service_container]
Run Code Online (Sandbox Code Playgroud)
你会有:
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)
这种做法很有争议,所以我建议您快速阅读以下内容:
| 归档时间: |
|
| 查看次数: |
10040 次 |
| 最近记录: |