如何在 Symfony 5.4+ 中通过其类名获取服务的标签

How to get tag of the service by its class name in Symfony 5.4+

提问人:Hevyweb 提问时间:11/12/2023 最后编辑:Hevyweb 更新时间:11/16/2023 访问量:41

问:

初始信息:Symfony 5.4+,PHP 8+。

例如,我有一个类 EventService。它是 EventInterface 类型的构造函数中的第一个参数。

<?php
class EventService 
{
    public function __construct(private EventInterface $event)
    {
    }

    public function execute()
    {
     // obtain tags of the $event
    }
}

有几个事件实现了此接口

<?php

class Event implements EventInterface 
{
// no tags property in here
}

在service.yaml中,我声明

Event:
  public: true
  tags:
    - { name: 'foo', priority: 20 } 
    - { name: 'bar', priority: -10 } 

如何获取EventService中$event对象的“foo”和“bar”标签?

我尝试使用ContainerBuilder,但它给了我一个错误“找不到服务”。

$containerBuilder->findDefinitions($event::class)->getTags()
PHP symfony 标签

评论

0赞 Cerad 11/12/2023
您是否正在使用编译器通道?
0赞 hakre 11/12/2023
我编辑了您的问题,请检查我是否没有错误地更改任何内容(特别是 get 和 Tags() 之间的空格)。对于“(如果有)”,这是否意味着您当前没有 YAML 文件中的服务?我猜你不想把这作为一个要求,对吧?
0赞 Hevyweb 11/12/2023
那,@hekra。是的,该类可能有也可能没有标记。因此,如果该类被标记,我的 listerer 类应该对其应用额外的逻辑。问题是我不能简单地解析service.yaml,因为供应商中可能有另一个service.yaml
0赞 Skuti 11/12/2023
“service.yaml 文件中定义的该类的标签”是什么意思。你是说标签迭代器?

答: 暂无答案