micro-module/decorator-bundle

Symfony 捆绑包,用于处理服务容器中的装饰器

v1.1.4 2022-06-07 08:53 UTC

This package is auto-updated.

Last update: 2024-09-07 13:36:57 UTC


README

Gitter Build Status Dependency Status Average time to resolve an issue Percentage of issues still open

为 Symfony 依赖注入容器提供一致的装饰器处理。

安装

对于 Symfony 3.3 至 4

composer require internations/decorator-bundle

对于 Symfony < 3.3

composer require internations/decorator-bundle:~0

使用方法

"装饰此"-模式

在 "装饰此"-模式中,你将在依赖项中声明你的装饰器。一个配置示例

<service id="iterator" class="ArrayIterator">
    <argument type="collection">
        <argument type="string">element1</argument>
        <argument type="string">element2</argument>
    </argument>
    <tag name="decorator.decorate_this" decorator_id="infinite_iterator"/>
</service>

<service id="infinite_iterator" class="InifiteIterator" public="false">
    <argument type="service" id="__subject__"/>
</service>

上面的配置将创建此实例

$iterator = new InfiniteIterator(
    new ArrayIterator(['element1', 'element2'])
);

"装饰其他"模式

在 "装饰其他"-模式中,你将在装饰器定义本身中声明你要装饰的主题。一个配置示例

<service id="iterator" class="ArrayIterator">
    <argument type="collection">
        <argument type="string">element1</argument>
        <argument type="string">element2</argument>
    </argument>
</service>

<service id="infinite_iterator" class="InifiteIterator" public="false">
    <argument type="service" id="__subject__"/>
    <tag name="decorator.decorate_other" service_id="iterator"/>
</service>

上面的配置将再次创建此实例

$iterator = new InfiniteIterator(
    new ArrayIterator(['element1', 'element2'])
);

指定优先级

为了控制装饰的顺序,支持为装饰器设置优先级标志。优先级可以是 PHP_INT_MAX-PHP_INT_MAX 之间的任何值,默认优先级是 0

<service id="infinite_iterator" class="InifiteIterator" public="false">
    <argument type="service" id="__subject__"/>
    <tag name="decorator.decorate_other" service_id="iterator" priority="255"/>
</service>

以编程方式使用捆绑包

在需要在外部 XML 配置之外重用装饰功能的情况下,你可以在你的 Compiler Pass 中使用以下 API。以下是一个示例,添加装饰服务 common_service 使用装饰器 special_decorator 和优先级 255

namespace …;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use InterNations\Bundle\DecoratorBundle\Tagger\DecorationTagger;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class MyCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        DecorationTagger::tag($container, 'common_service', 'special_decorator', 255);
    }
}

致谢

基于 Dovydas Bartkevicius 的想法,并得到 Max Beutel 的大量反馈。