julienfalque/symfony-service-replacer

允许在运行时替换 Symfony 依赖注入容器中的服务

1.0.x-dev 2021-10-02 16:22 UTC

This package is auto-updated.

Last update: 2024-08-29 05:31:24 UTC


README

提供了一种在测试目的下,在运行时替换 Symfony 依赖注入容器中服务的途径。

安装

使用 Composer 安装此包

$ composer require --dev julienfalque/symfony-service-replacer

然后在你的 Symfony 应用程序中启用该包

<?php // config/bundles.php

return [
    // ...
    JulienFalque\SymfonyServiceReplacer\Bridge\Symfony\Bundle::class => ['test' => true],
];

该包装饰了 Symfony 的测试容器(test.service_container),确保通过启用 FrameworkBundle 的测试模式来使其可用

# config/packages/test/framework.yaml
framework:
  test: true

使用方法

要使服务在运行时可替换,请将其添加到 replaceable 标签中

# config/services.yaml
services:
  replaceable_service:
    # ...
    tags: [replaceable]

每个标记的服务都由一个代理装饰,该代理将调用转发到原始服务并返回其结果不变。标记的服务无需公开即可替换。

在运行时,测试容器(test.service_container)现在允许您使用 set() 方法替换您的服务,并使用 restore() 方法再次使用原始服务

$service = $container->get('replaceable_service');

echo "{$service->foo()}\n";

$container->get('test.service_container')->set('replaceable_service', new class() {
    public function foo(): string
    {
        return 'Bar';
    }
});

echo "{$service->foo()}\n";

$replacer->restore('replaceable_service');

echo "{$service->foo()}\n";

假设原始服务的方法返回 "Foo",这将输出

Foo
Bar
Foo