PHP 8.6的Symfony应用需要按json或csv选择导出器时,可以给每个导出服务添加同一个标签及format属性,再注入带索引的服务迭代器。新增导出格式只需实现接口并注册标签,选择逻辑不必反复增加容器取服务代码。
约定接口与两种实现
下面代码放在已启用服务自动装配的symfony 8.1应用中,每个类按psr-4放进对应文件。示例输入是已完成权限过滤的小型二维列表。
namespace App\Export;
interface Exporter { public function render(array $rows): string; }
final class JsonExporter implements Exporter {
public function render(array $rows): string {
return json_encode($rows, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
}
}
final class CsvExporter implements Exporter {
public function render(array $rows): string {
$f = fopen('php://temp', 'w+');
if ($f === false) throw new \RuntimeException('Cannot open buffer');
try {
foreach ($rows as $row) {
if (fputcsv($f, $row, ',', '"', '') === false)
throw new \RuntimeException('CSV write failed');
}
rewind($f);
$csv = stream_get_contents($f);
if ($csv === false) throw new \RuntimeException('CSV read failed');
return $csv;
} finally { fclose($f); }
}
}
实际写入CSV供表格软件打开时,还需按字段业务处理公式注入。这里的插件选择机制不承担不可信文本的表格转义策略。

Adding Attributes to Tags:官方文档示例
用标签属性建立格式索引
保留现有services.yaml的_defaults和资源扫描,在services下面添加三项。不要为使用标签而重写整份项目配置。
services:
App\Export\JsonExporter:
tags: [{ name: app.exporter, format: json }]
App\Export\CsvExporter:
tags: [{ name: app.exporter, format: csv }]
App\Export\ExportRouter:
autowire: true
public: false
format必须唯一。相同索引会让选择结果不再明确,应在开发检查或编译检查中拒绝重复格式。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

Referencing Tagged Services:官方文档示例
注入迭代器并拒绝未知格式
在调用方注入ExportRouter,通过render完成选择。请求格式只能作为白名单选择值,不参与类名拼接或任意容器ID查找。
namespace App\Export;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
final class ExportRouter {
public function __construct(
#[AutowireIterator('app.exporter', indexAttribute: 'format')]
private iterable $exporters
) {}
public function render(string $format, array $rows): string {
foreach ($this->exporters as $key => $exporter) {
if ($key === $format) return $exporter->render($rows);
}
throw new \InvalidArgumentException('Unsupported export format');
}
}
分别请求json、csv和未注册格式,检查输出与异常。服务标签负责组织插件,不代表浏览器请求已经获得读取数据的权限;认证、字段过滤和响应头由接口层处理。

Tagged Services with Index:官方文档示例
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










