互联网上已经有很多关于将服务注入到另一个服务中的文档,如下所示: 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 以便将用户注入到我的新服务中?
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?
感谢qooplmao的评论,帮助我找到答案,因为这正是我想要的。我想我会为了其他人的利益回答我自己的问题,因为我现在有这个工作,加上对评论中语法的一些更正。
我应该寻找的是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文档有礼貌地在引用它的页面上提供指向这些关键信息的链接就好了!