setono/composite-compiler-pass

为 Symfony 设计的复合编译器传递,使其创建复合服务更加容易

v1.2.0 2024-06-07 07:51 UTC

This package is auto-updated.

Last update: 2024-09-07 08:19:59 UTC


README

Latest Version Software License Build Status Code Coverage Mutation testing

当你使用复合服务时,你会发现自己一遍又一遍地编写相同的编译器传递。这个库会为你提供所需的编译器传递,这样你就无需再考虑它了。

安装

composer require setono/composite-compiler-pass

使用方法

假设你有一个这样的复合服务

<?php
final class YourCompositeService
{
    /**
     * @var list<object>
     */
    private array $taggedServices = [];

    public function add(object $taggedService): void
    {
        $this->taggedServices[] = $taggedService;
    }
}

该服务的 ID 为 your_bundle.your_service,并且你想自动将带有 tag 标签的服务添加到这个复合服务中。

在你的包类中执行以下操作

<?php

use Setono\CompositeCompilerPass\CompositeCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

final class YourBundle extends Bundle
{
    public function build(ContainerBuilder $container): void
    {
        $container->addCompilerPass(new CompositeCompilerPass('your_bundle.your_service', 'tag'));
    }
}

注意 你甚至可以定义具有优先级的标签服务,它们将在添加到复合服务之前自动排序。这归功于在底层使用的 Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait

包含复合服务

如果你愿意,这个库还提供了一个小的抽象类,你可以基于它创建复合服务。类名为 CompositeService,你可以在这里找到它。

以下是一个使用示例

<?php

use Setono\CompositeCompilerPass\CompositeService;

/**
 * @property list<TaggedServiceInterface> $services
 *
 * @extends CompositeService<TaggedServiceInterface>
 */
final class ConcreteCompositeService extends CompositeService implements TaggedServiceInterface
{
    public function process(): void
    {
        foreach ($this->services as $service) {
            // Both your IDE, Psalm, and PHPStan knows that $service is an instance of TaggedServiceInterface
        }
    }
}

interface TaggedServiceInterface
{

}