在把这段生成的导出器工厂连接到请求参数前,对它进行审查。
只接受 csv 与 json 两个键;把它们映射到由 PSR-4 加载且实现 Exporter 的导出器;在自动加载前拒绝未知键;并返回选中的实例。
php
<?php
declare(strict_types=1);
namespace App\Reports;
use App\Contracts\Exporter;
use App\Reports\Exporters;
final class ExporterFactory
{
public function create(string $format): Exporter
{
$class = 'Exporters\\' . ucfirst($format) . 'Exporter';
if (!class_exists($class)) {
throw new \InvalidArgumentException('Unknown export format');
}
return new $class();
}
}
生成代码仅作示例,不代表任何特定模型