jeudi 19 juillet 2018

How can I create a controller constructor that takes in two concrete implementations of the same interface?

Background

Note: this is using Laravel 5.3, Please don't judge.

We are trying to use dependency injection with our laravel controllers and push as much business logic into repos that are injected to controllers upon the controller instantiation.

We already have this functioning example:

class AcmeController extends Controller
{
    protected $repository;

    public function __construct(AcmeInterface $repository)
    {
        $this->repository = $repository;
    }
}     

inside app/Providers/RepositoryServiceProvider.php we do the binding:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(\App\Repositories\Contracts\AcmeInterface::class, \App\Repositories\OpCity\AcmeRepo::class);
    }
}

and then the AcmeRepo naturally implements the AcmeInterface:

class AcmeRepo implements AcmeInterface

Question

right now we have a case where some of the data of the same model is persisted in a memory type storage (redis) and the rest is persisted in relational db storage (psql). We would like to have two separate repos where each repo is specific to its storage type, ie RedisAcmeRepo and SqlAcmeRepo

How is it possible to do this in the AcmeController constructor?

public function __construct(AcmeInterface $sqlRepo, AcmeInterface $redisRepo)
{
    $this->sqlRepo = $sqlRepo;
    $this->redisRepo = $redisRepo;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire