Thursday 31 October 2019

Laravel creating an interface and implementation dynamically

Somehow you need to run a different implementation depending on system environment This is what i have done for one of my case
In your .env file

DOCUMENT_INTERFACE=GoogleCloud
#DOCUMENT_INTERFACE=LocalStorage
In my AppServiceProvider.php


   use Illuminate\Support\Facades\App;
   public function register()
    {
        $this->app->bind(DocumentInterface::class, function () {
            $className = 'Path\To\Interfaces' . '\\' . env('DOCUMENT_INTERFACE') . 'Implementation';
            $class = App::make($className);
            return new $class();
        });
    }
       
DocumentInterface.php

interface DocumentInterface
{
    public function create(DocumentUpload $documentUpload);
}

GoogleCloudImplementation.php


class GoogleCloudImplementation implements DocumentInterface
{
    public function create(DocumentUpload $documentUpload)
    {
       
    }
}

LocalStorageImplementation.php


class LocalStorageImplementation implements DocumentInterface
{
    public function create(DocumentUpload $documentUpload)
    {
       
    }
}

Share:

0 comments:

Post a Comment

Popular Posts

Recent Posts

Pages

Powered by Blogger.

About Me

My photo
For the past 10 years, I've been playing with codes using PHP, Java, Rails. I do this for a living and love new things to learn and the challenges that comes with it. Besides programming I love spending time with friends and family and can often be found together catching the latest movie or planning a trip to someplace I've never been before.