互联网上已有大量关于将服务注入其他服务的文档,如下所示:http://symfony.com/doc/current/components/dependency_injection/introduction.html
但是,我已经有了一个名为 ObjectCache
的服务,它在symfony的services.yml中配置如下:
object_cache:
class: App\Bundle\ApiBundle\Service\ObjectCache
此服务目前有两种获取和设置User对象的方法 . 例如:
$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以便将User注入我的新服务?
object_cache:
class: App\Bundle\ApiBundle\Service\ObjectCache
some_service:
class: App\Bundle\ApiBundle\Service\SomeService
arguments: [@object_cache->getUser()????]
这不起作用,symfony yaml文档至少可以说是粗略的 .
我基本上是被迫创建ObjectCache的User-only风格并将其注入SomeService或期望SomeService接收ObjectCache并在构造函数中调用getUser一次?
1 回答
感谢qooplmao的评论,帮助我找到答案为this is exactly what I was looking for . 我以为我会回答我自己的问题,为了其他人的利益 I now have this working ,加上对评论语法的一些修正 .
我应该一直在寻找的是Symfony的 Expression Language ,它可以精确地控制我正在寻找的控制粒度 .
生成的配置现在如下所示:
有关表达式语法的更多信息,请参阅以下详细文档:http://symfony.com/doc/2.7/components/expression_language/syntax.html
(如果只有Symfony文档有礼貌的话,可以在引用它的页面上提供这些重要信息的链接!)