Lock Lock - 3 months ago 13
PHP Question

How to switch interfaces in Laravel whilst developing

I am building a

Laravel 5.2
App that will connect to a database that I don't have available to me whilst developing (it is a legacy database that I cannot install locally).

What is the cleanest way in Laravel to build my application so that I can develop using one interface, and then switch over to another when I push my project to the live environment?

In the past, I've had 2 classes, both of which have the same functions, and then in a configuration file, I would say which class it uses. Just wandering if there is a better way using Laravel? Or if there is a way of doing this already baked in?

Answer

One way I can think of achieving this is to switch the instance of the dependency injection when you're on local and production environment.

class ControllerExample 
{
    public function index( SomeInterface $data ) 
    {
        //...
    }
}

So in this example the controller index method needs SomeInterface which would be injected automatically. For local development you can resolve this interface to your stub class and for production you can switch to the real class. You can do this by registering the binding of the interface in the app / Providers / AppServiceProvider.php in the register() method:

if ($this->app->environment() == 'local') {
    $this->app->when('App\Your\ControllerExample')
        ->needs('App\SomeInterface')
        ->give('App\YourStubbedClass');
} else {
    $this->app->when('App\Your\ControllerExample')
        ->needs('App\SomeInterface')
        ->give('App\YourRealClassWorkingWithTheRealDatabase');
}

What this basically does is when your env is local the dependency in your controller will be resolved with the stub class, otherwise on other envs it will be the real class.

Comments