2013-07-05 32 views
2

當我擴展ContainerAware或實現ContainerAwareInterface時,服務不會調用setContainer。創建實現ContainerAwareInterface的服務

class CustomService implements ContainerAwareInterface 
{ 
    public function setContainer(ContainerInterface $container = null) 
    { 
     $this->container = $container; 
    } 
} 

如何從我的服務中使用容器而不注入一個? 是否需要將容器對象傳遞給構造函數或setter?

+0

這是你滿級或者只是一個子集? $ this->容器不存在於你的類中。請顯示您的「使用」語句 – saamorim

+0

您是否嘗試在您的服務定義中設置調用參數以調用setContainer方法將service_container作爲參數傳遞? – Picoss

回答

7

讓你services.yml文件

services: 
    bundle.service_name: 
     class: ... 
     calls: 
      - [ setContainer, [ @service_container ] ] 
+0

我的確如此,但現在整個應用程序只是掛起 – Zennichimaro

+0

什麼是錯誤? –

+0

你必須把服務名稱裏面大衣: 服務: bundle.service_name: 類:... 電話: - [setContainer,[ '@service_container'] – Cedo

3

只有實現ContainerAwareContainerAwareInterface是不夠的定義。您必須以service_container作爲參數來調用setter注入。 但不建議注入完整的容器。更好地只注入您真正需要的服務。

4

你必須把服務名稱引號內:

services: 
    bundle.service_name: 
     class: ... 
     calls: 
      - [ setContainer, [ '@service_container' ]] 
1

這是一個容器感知服務的完整實現示例。

但應注意避免注射整個容器。最好的做法是僅注入所需的組件。有關該主題的更多信息,請參閱Law of Demeter - Wikipedia

爲此,該命令將幫助你找到所有可用的服務:

# symfony < 3.0 
php app/console debug:container 

# symfony >= 3.0 
php bin/console debug:container 

不管怎樣,下面是完整的例子。

app/config/services.yml文件:

app.my_service: 
    class: AppBundle\Service\MyService 
    calls: 
     - [setContainer, ['@service_container']] 

服務類src/AppBundle/Service/MyService.php

<?php 

namespace AppBundle\Service; 

use Symfony\Component\DependencyInjection\ContainerAwareInterface; 
use Symfony\Component\DependencyInjection\ContainerAwareTrait; 

class MyService implements ContainerAwareInterface 
{ 
    use ContainerAwareTrait; 

    public function useTheContainer() 
    { 
     // do something with the container 
     $container = $this->container; 
    } 
} 

而且finaly控制器在src/AppBundle/Controller/MyController.php

<?php 

namespace AppBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\Response; 

/** 
* My controller. 
*/ 
class MyController extends Controller 
{ 
    /** 
    * @Route("/", name="app_index") 
    * @Method("GET") 
    */ 
    public function indexAction(Request $request) 
    { 
     $myService = $this->get('app.my_service'); 
     $myService->useTheContainer(); 

     return new Response(); 
    } 
}