codemonkeys-ru/repository-alias-bundle
composer require codemonkeys-ru/repository-alias-bundle
AppKernel.php:
new CodeMonkeysRu\RepositoryAliasBundle\RepositoryAliasBundle(),
config.yml):
repository_alias:
repository_key: "app.repo" # Custom prefix for your repositories
repository:
user: AppBundle:User
product: AppBundle:Product
Replace verbose repository calls:
// Before
$repo = $this->getDoctrine()->getRepository('AppBundle:User');
// After
$repo = $this->get('app.repo.user');
Define Aliases:
Use YAML/XML/annotation to map short names (e.g., user) to Doctrine entities (e.g., AppBundle:User).
repository:
admin: AppBundle:AdminUser
category: AppBundle:Category
Inject via DI:
class UserService {
public function __construct(
private RepositoryAlias $repositoryAlias
) {}
public function getUserRepo() {
return $this->repositoryAlias->get('app.repo.user');
}
}
Leverage Shortcuts:
// Direct service call
$repo = $this->get('app.repo.category');
// With entity creation helper
$category = $this->get('app.repo.category')->newEntity('Electronics');
Symfony Forms: Use aliases in form type factories to simplify repository access:
$builder->add('category', EntityType::class, [
'class' => $this->get('app.repo.category')->getEntityName(),
]);
Command Bus: Pass repository aliases as arguments to commands/services:
$command->setRepository($this->get('app.repo.user'));
Event Subscribers: Access repositories via alias in event handlers:
$user = $this->get('app.repo.user')->find($event->getUserId());
Namespace Collisions:
Avoid overlapping repository keys (e.g., user and user_profile). Use prefixes like admin.user or api.user.
Caching Quirks:
Clear Symfony cache after changing config.yml:
php bin/console cache:clear
Doctrine Proxy Issues:
If using proxies, ensure the alias bundle’s getOriginalRepository() method is called when needed:
$originalRepo = $this->get('app.repo.user')->getOriginalRepository();
Deprecated Methods:
Avoid getAliasFor() (v0.1.2) in new code; prefer direct service injection.
Verify Alias Exists:
Check if the alias is registered in config.yml and the bundle is enabled in AppKernel.php.
php bin/console debug:container | grep app.repo
Entity Not Found:
Ensure the FQCN (e.g., AppBundle:User) matches your entity namespace and Doctrine metadata.
Dynamic Aliases:
Override the RepositoryAliasExtension to load aliases dynamically (e.g., from a database):
# config.yml
repository_alias:
extensions:
- AppBundle\DynamicRepositoryAliasExtension
Custom Repository Methods: Decorate repositories to add bundle-specific methods:
$repo = $this->get('app.repo.user');
$repo->customMethod(); // If extended via decorator
Testing:
Mock the RepositoryAlias service in tests:
$this->container->set('app.repo.user', $this->createMock(Repository::class));
How can I help you explore Laravel packages today?