2014-12-05 23 views
2

我想在我的Repository中獲取當前的語言環境。這就是爲什麼我要將容器注入到Repository中,但出現錯誤,我無法弄清楚。 這是我service.yml代碼在Entity Repository中注入容器

survey.repository.container_aware: 
    class: Demo\SurveyBundle\Repository\SurveyRepository 
    calls: 
     - [ setContainer, [ @service_container ] ] 

,這是我的倉庫類代碼

....... 

use Symfony\Component\DependencyInjection\ContainerInterface as Container; 

....... 

protected $container; 

public function __construct(Container $container) { 
    $this->container = $container; 
} 

之後,我收到以下錯誤

ContextErrorException: Catchable Fatal Error: Argument 1 passed to 
Demo\SurveyBundle\Entity\SurveyRepository::__construct() must implement 
interface Symfony\Component\DependencyInjection\ContainerInterface, instance of 
Doctrine\ORM\EntityManager given 

我很想念我的構建或服務?

+0

爲什麼你要注入整個容器?請更精確地嘗試直接注入您所依賴的服務。 – Basster 2014-12-05 10:52:06

回答

1

您未將容器傳遞給構造函數,而是傳遞給setContainer。所以,你在shouuld SurveyRepository聲明的公共方法setContainer

演示/ SurveyBundle /實體/ SurveyRepository.php

protected $container; 

public function setContainer(Container $container) { 
    $this->container = $container; 
} 

或容器傳遞給構造函數:

DemoSurveyBundle/Resources/Config/services.yml

survey.repository.container_aware: 
    class: Demo\SurveyBundle\Repository\SurveyRepository 
    arguments: [@service_container] 

編輯: 順便說一句,如果你只需要區域設置,不足以傳遞%locale%參數而不是整個容器?

survey.repository.container_aware: 
    class: Demo\SurveyBundle\Repository\SurveyRepository 
    calls: 
     - [ setLocale, [ %locale%] ] 

protected $locale; 

public function setLocale($locale) { 
    $this->locale = $locale; 
} 
+1

如果Repository類擴展了已經有構造函數的'Doctrine \ ORM \ EntityRepository',我認爲這不起作用。 – Matteo 2014-12-05 07:42:31

+0

因此,請採取第一種選擇。在存儲庫類中聲明setContainer。 – devilcius 2014-12-05 07:46:27

+0

順便說一句,@Matteo,將不足以將%locale%傳遞到存儲庫? – devilcius 2014-12-05 07:59:53

3

你傳入容器與Setter Injection(在YML),但你在構造類中定義它。

BTW實體管理器已經有參數的構造函數類,所以不要拿Constructor Injection和簡單地改變你的方法在類如:

public function setContainer(Container $container) { 
    $this->container = $container; 
} 
3

你確實有另一個主要問題在這裏。從錯誤信息中可以明顯看出,您正嘗試使用實體管理器訪問您的教義存儲庫。喜歡的東西:

$repo = $em->getRepository('whatever'); 

從未被使用的服務容器代碼,它其實並不重要,你做什麼,你還是不會讓你的容器注入。將存儲庫作爲服務創建需要將實體管理器用作工廠,並在services.yml文件中佔用一些額外的行。

喜歡的東西:

# services.yml 
cerad_person.person_repository.doctrine: 
    class: Cerad\Bundle\PersonBundle\Entity\PersonRepository 
    factory_service: 'doctrine.orm.default_entity_manager' 
    factory_method: 'getRepository' 
    arguments: 
     - 'Cerad\Bundle\PersonBundle\Entity\Person' 
    calls: 
     - [ setContainer, [@container] ] 

// controller 
$personRepo = $this->get('cerad_person.person_repository.doctrine'); 

這會給你注入容器的存儲庫。

@devilciuos - %locale%只會給你默認的語言環境,而不會在請求中作爲_locale傳遞。不幸的是,它似乎需要聽衆通過服務訪問本地請求:https://github.com/symfony/symfony/issues/5486