您的当前位置:首页正文

44. 服务容器 标记服务

来源:要发发知识网

有时候,你可能需要解析某个「分类」下的所有绑定。例如,你正在构建一个报表的聚合器,它接收一个包含不同 Report 接口实现的数组。注册了 Report 实现后,你可以使用 tag 方法为其分配标签:

$this->app->bind('SpeedReport', function () {
    //
});

$this->app->bind('MemoryReport', function () {
    //
});

$this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');

服务被标记后,你可以通过 tagged 方法轻松地将它们全部解析:

$this->app->bind('ReportAggregator', function ($app) {
    return new ReportAggregator($app->tagged('reports'));
});