已經有大量的文檔在互聯網上關於注射服務到另一個這樣的服務: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一次?
服務工廠是你在找什麼:http://symfony.com/doc/current/components/dependency_injection/factories.html你將最終與一個可注射的物體ct_cache_user服務。 – Cerad
您可以使用表達式語言,比如'「@service('object_cache')。getUser」'(參見http://symfony.com/doc/2.7/book/service_container.html#using-the-expression-language)。 – qooplmao