Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compiler pass to declare a repository as service for each declared doctrine entity in a symfony application
<?php
final class RegisterRepositoriesForAllEntitiesPass implements CompilerPassInterface
{
/** {@inheritdoc} */
public function process(ContainerBuilder $container)
{
/** @var MappingDriver $metadata */
$metadata = $container->get($this->mappingDriverServiceName());
$entityManagerReference = new Reference('doctrine.orm.entity_manager');
Assert::isInstanceOf($metadata, MappingDriver::class);
$allClassNames = $metadata->getAllClassNames();
$repositoryDefinitions = array_combine(
array_map(static function (string $entity): string {
return $entity.'.repository';
}, $allClassNames),
array_map(
static function (string $entity) use ($entityManagerReference): Definition {
$definition = new Definition(EntityRepository::class);
$definition->setFactory([$entityManagerReference, 'getRepository']);
$definition->setArgument(0, $entity);
return $definition;
},
$allClassNames
)
);
Assert::isArray($repositoryDefinitions);
$container->addDefinitions($repositoryDefinitions);
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment