2014-01-15 66 views
4

我是Symfony 2的新手,嘗試創建一些簡單的應用程序來學習。我創建了一個包GoogleApiBundle。捆裏面,我有一個控制器YouTubeController,這是一種服務:Symfony 2服務容器爲空

//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->containerNULL

我搜索了但沒有得到答案。我做錯了嗎?

回答

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); 
    } 
} 

這種做法是非常有爭議的,所以我建議你在這些快速閱讀:

+0

謝謝。我得到異常'ServiceNotFoundException:服務「myname_googleapi_youtube」有一個依賴於一個不存在的服務「session_container」。' – DrXCheng

+0

哈哈對不起,它是'service_container' :)我更新了代碼 – Mick

+2

完美!謝謝! – DrXCheng