services.yamlとDI
symfonyのservices.yamlはservice locatorやDI containerのような役割を果たします。
symfonyにおいて依存の逆転を行う場合にはservices.yamlにinterfaceとそれに対応する具象クラスのマッピングを記述することが多いと思います。
例えば戦術的DDDアーキテクチャに沿ってDomain, Application, Presentation, Infrastructureとレイヤーを分けている場合、Application layerのクラスのコンストラクタではDomain layerに属するRepositoryInterfaceが注入されると思います。
RepositoryInterfaceは具象クラスではないからそのままでは動作しません。
services.yamlでそのinterfaceに対応する具象クラスのRepositoryをマッピングする必要があります。
新しいRepositoryを定義するたびにservices.yamlに定義するのは面倒です!もうちょっといわゆる“設定よりも規約”なアプローチを紹介します。
実装例
symfonyではKernel.phpという仕組みがあり、ここでアプリケーションで利用するクラスやオブジェクトの設定を行います。Kernel.phpに以下のような定義をします。
class Kernel extends BaseKernel
{
use MicroKernelTrait;
protected function build(ContainerBuilder $container): void
{
$container->addCompilerPass(new RepositoryCompilerPass()); // ここで自動で登録するレポジトリクラスのルールを定義する
// API Platformのmapping.pathsに動的に追加
$container->loadFromExtension('api_platform', [
'mapping' => [
'paths' => $paths,
],
]);
}
}
RepositoryCompilerPassは以下の通りに実装します。
class RepositoryCompilerPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container): void
{
$this->tagRepositoryServices($container);
$this->aliasRepositoryInterfaces($container);
}
/**
* Infrastructure/Repository内のリポジトリクラスに`doctrine.repository_service`タグを追加します。
*
* @param ContainerBuilder $container コンテナビルダー
*/
private function tagRepositoryServices(ContainerBuilder $container): void
{
$projectDir = $container->getParameter('kernel.project_dir');
$finder = new Finder();
$finder->files()->in($projectDir . '/src')->path('/Infrastructure\/Repository/')->name('*Repository.php');
foreach ($finder as $file) {
$relativePath = \str_replace([$projectDir . '/src/', '.php'], '', $file->getRealPath());
$className = \sprintf('App\\%s', \str_replace('/', '\\', $relativePath));
// クラスが存在し、かつサービス定義がある場合にタグを追加
if (\class_exists($className) && $container->hasDefinition($className)) {
$definition = $container->getDefinition($className);
$definition->addTag('doctrine.repository_service');
}
}
}
/**
* `doctrine.repository_service`タグが付与されたサービスに対し、対応するインターフェースにエイリアスを設定します。
*
* @param ContainerBuilder $container コンテナビルダー
*/
private function aliasRepositoryInterfaces(ContainerBuilder $container): void
{
foreach ($container->findTaggedServiceIds('doctrine.repository_service') as $id => $tags) {
$definition = $container->getDefinition($id);
$interfaces = \class_implements($definition->getClass());
foreach ($interfaces as $interface) {
if (\str_contains($interface, 'Domain\\Repository')) {
// インターフェースにエイリアスを設定
$container->setAlias($interface, $id)
->setPublic(false);
}
}
}
}
}
このクラスではtagRepositoryServices() → aliasRepositoryInterfaces()の順番で実行されています。
tagRepositoryServicesではプロジェクトのInfrastructure/Repositoryの中にあるsuffixがRepository.phpとなっているクラスを全て取得し、それらのクラスにdoctrine.respository_serviceタグを付与しています。
その次に実行されるaliasRepositoryInterfacesではdoctrine.respository_serviceタグがついた全てのクラスのインターフェースを読み取り、intefaceにエイリアスを設定することでinterfaceと具象のRepositoryクラスを紐づけています。
例えばapp/src/Infrastructure/Repository/FooRepository.phpとapp/src/Domain/Repository/FooRepositoryInterface.phpを以下のように定義します。
class FooRepository implements FooRepositoryInterface
{
// some logic
}
interface FooRepositoryInterface
{
// some inteface
}
Application Serviceを以下のように実装します。
class SomeService
{
public function __construct(
private readonly FooRepositoryInterface $repository
){
}
}
通常はservices.yamlにFooRepositoryInterfaceとFooRepositoryのマッピング設定を書く必要がありますが、今回の設定によってその設定は不要になり自動でFooRepositoryが利用されます。
終わりに
今回はRepositoryInterfaceに自動でエイリアスを貼る方法を説明しましたが、これを応用することで例えば環境変数によってInterfaceに対応づける具象クラスを差し替えたりすることもできたりもします(弊社リピストでは実際に活用しています)。これこそがまさにDependency Injectionの恩恵だと思います。