2016-02-27 37 views
1

已經有大量的文檔在互聯網上關於注射服務到另一個這樣的服務:http://symfony.com/doc/current/components/dependency_injection/introduction.html是否有可能注入的方法到服務symfony的services.yml

不過,我已經叫服務ObjectCache這是在symfony中的services.yml配置是這樣的:

object_cache: 
    class: App\Bundle\ApiBundle\Service\ObjectCache 

該服務目前擁有用於獲取和設置用戶對象的兩種方法。例如:

$user = new User(); // assume entity from database 
$this->get('object_cache')->setUser($user); 
// ... 
$this->get('object_cache')->getUser(); // instance of $user 

我想創建一個新的服務,這總是取決於用戶,所以有意義的注入在服務創建用戶:

class SomeService { 
    public function __construct(User $user) 
    { 
    } 
} 

我將如何配置services.yml這樣用戶注入我的新服務?

object_cache: 
    class: App\Bundle\ApiBundle\Service\ObjectCache 
some_service: 
    class: App\Bundle\ApiBundle\Service\SomeService 
    arguments: [@object_cache->getUser()????] 

這沒有奏效,symfony yaml文檔很粗略,至少可以說。

我基本上被迫創建ObjectCache的用戶唯一的味道,並將其注入到SomeService或期望SomeService接收ObjectCache並在構造函數中調用getUser一次?

+2

服務工廠是你在找什麼:http://symfony.com/doc/current/components/dependency_injection/factories.html你將最終與一個可注射的物體ct_cache_user服務。 – Cerad

+2

您可以使用表達式語言,比如'「@service('object_cache')。getUser」'(參見http://symfony.com/doc/2.7/book/service_container.html#using-the-expression-language)。 – qooplmao

回答

1

感謝qooplmao的評論幫助我找到答案this is exactly what I was looking for。我想我會回答我自己的問題,爲他人的利益我現在有這個工作,加上一些更正的語法在評論。

我應該一直在尋找的東西是Symfony的表達式語言,它允許精確地控制我想要的粒度。

生成的配置現在看起來是這樣的:

object_cache: 
    class: App\Bundle\ApiBundle\Service\ObjectCache 
some_service: 
    class: App\Bundle\ApiBundle\Service\SomeService 
    arguments: [@=service('object_cache').getUser()] 

有關表達式語法的詳細信息,下面是一些詳細的文檔:http://symfony.com/doc/2.7/components/expression_language/syntax.html

(如果只Symfony的文檔有禮節提供鏈接這些關鍵信息在頁面上引用它!)

相關問題