alsciende / make-registry-bundle
Symfony Maker Bundle 扩展,用于为标记的服务创建注册表
1.0.0
2024-04-19 09:55 UTC
Requires
- symfony/maker-bundle: ^1.55
README
此 Symfony 扩展向控制台添加了 make:registry
命令。使用此生成器将为您的应用程序中的专用服务注册表创建基本组件
- 一个接口,描述注册表提供的服务类型
- 实现该接口的示例服务
- 配置为注册实现您接口的所有服务的服务注册表
示例
执行 php bin/console make:registry OutputFormatter
将创建以下类
// src/OutputFormatter/OutputFormatterInterface.php
<?php
namespace App\OutputFormatter;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
#[AutoconfigureTag('app.output_formatter')]
interface OutputFormatterInterface
{
public function getName(): string;
}
// src/OutputFormatter
<?php
namespace App\OutputFormatter;
class SampleOutputFormatter implements OutputFormatterInterface
{
public function getName(): string
{
return 'sample';
}
}
// src/OutputFormatter/OutputFormatterRegistry.php
<?php
namespace App\OutputFormatter;
use Symfony\Component\DependencyInjection\Attribute\AsAlias;
use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
#[AsAlias('app.output_formatter_registry')]
class OutputFormatterRegistry
{
/**
* @var array<OutputFormatterInterface>
*/
private array $services = [];
public function __construct(
#[TaggedIterator('app.output_formatter')]
iterable $services
) {
foreach ($services as $service) {
if ($service instanceof OutputFormatterInterface) {
$name = $service->getName();
if (array_key_exists($name, $this->services)) {
$duplicate = $this->services[$name];
throw new \LogicException(sprintf('Service name "%s" duplicate between %s and %s.', $name, $duplicate::class, $service::class));
}
$this->services[$name] = $service;
}
}
}
/**
* @return array<string>
*/
public function getNames(): array
{
return array_keys($this->services);
}
/**
* @return array<OutputFormatterInterface>
*/
public function getOutputFormatters(): array
{
return $this->services;
}
public function getOutputFormatter(string $name): OutputFormatterInterface
{
if (array_key_exists($name, $this->services)) {
return $this->services[$name];
}
throw new \UnexpectedValueException(sprintf('Cannot find service "%s". Available services are %s.', $name, implode(',', $this->getNames())));
}
}
安装
确保已全局安装 Composer,如 Composer 文档的 安装章节 所述。
使用 Symfony Flex 的应用程序
打开命令行,进入您的项目目录,并执行
composer require --dev alsciende/make-registry-bundle
不使用 Symfony Flex 的应用程序
步骤 1: 下载 Bundle
打开命令行,进入您的项目目录,并执行以下命令以下载此 Bundle 的最新稳定版本
composer require --dev alsciende/make-registry-bundle
步骤 2: 启用 Bundle
然后,通过将其添加到项目 config/bundles.php
文件中注册的 Bundle 列表中来启用 Bundle
// config/bundles.php return [ // ... Alsciende\Bundle\MakeRegistryBundle\AlsciendeMakeRegistryBundle::class => ['all' => true], ];