dimanche 31 janvier 2016

Laravel multiple container bindings of same type

I have over 70 repositories for my models I would like to register a service provider for them. I am using Doctrine2.

Each repository extends DefaultRepository which in turn extends doctrines EntityRepository.

Since EntityRepository needs two parameters in constructor, I need to provide them, e.g.

$this->app->bind(PersonRepository::class, function($app) {
    return new PersonRepository(
        $app['em'],
        $app['em']->getClassMetaData(Person::class)
    );
});

But I would need to do it 70 times...

I could bind doctrines ObjectRepository interface or DefaultRepository class, but since some of the repositories have custom methods, I would need to manually type hint it then e.g. /** @var PersonRepository $person to get correct autocomplete. Which is not something I would like to do.

I didn't manage to get contextual bindings to work either. Even when I tried to bind doctrines EntityRepository.

The only thing that comes to mind now, is using a deferred provider and loading list of all repositories from filesystem (since I want this process to be automatic), then cache them in a file (in all environments except local) and bind them in a loop. But this seems a bit too much work to get this task done.

Is there any easy/preferred way to bind all repositories without writing 70 $this->app->bind lines?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire