php - Contextual binding of interface via config in laravel 5 -
lets assume have interface so:
interface repositoryinterface{ public function getbyid($id); }
this interface gets implemented x amount of classes.
as example:
class sqliterepository implements repositoryinterface{ public function getbyid($id) { return $id; } }
i have config file in config
folder(do note, not database.php
file, it's whole different file):
'default' => 'sqlite', 'connections' => [ 'sqlite' => [ 'database' => env('db_database', storage_path('database.sqlite')), ], 'some_other_db' => [ 'database' => env('db_database', storage_path('some_other_db')), ], ],
the connections
can anything. database, api, heck csv file.
the main idea behind can switch in between storage mediums changing config. don't ask me why i'm not using default laravel database
file, it's long story.
the problem:
i want able inject different implementations of repositoryinterface
controllers based on config file, along lines of this:
if(config::get('default') == 'sqlite') { // return new sqliterepository }
obviously way go here service providers. i'm not sure how approach issue. mean along lines of this:
class repositoryserviceprovider extends serviceprovider { public function register() { if(config::get('storage') == 'sqlite') { $this->app->singleton(sqliterepository::class, function ($app) { return new sqliterepository(config('sqliterepository')); }); } } }
but feels little wrong, not mention gives me 0 error control. don't want throwing errors in serviceprovider. need sort of contextual binding or along lines. have read the documentation regarding contextual binding it's no i'm looking for, refers rather concrete implementations of classes based on controller uses them.
i thinking more of abstract factory type of deal, but, again, i'm not sure how fit laravel's way of doing things.
any pointing in right direction appreciated.
interface repositoryinterface{ public function getbyid(); } ... ... class sqliterepository implements repositoryinterface{ public function getbyid() { return 1; } } ... ... class csvrepository implements repositoryinterface{ public function getbyid() { return 2; } } ... ... class monkeypoorepository implements repositoryinterface{ public function getbyid() { return 3; } } ... ... use repositoryinterface; class controller { public function __construct( repositoryinterface $repo ) { $this->repo = $repo; } public function index() { dd($this->repo->getbyid()); } }
on app provider;
public function register() { $this->app->bind( repositoryinterface::class, env('repository', 'monkeypoorepository' ) ); }
index method return (int)3
Comments
Post a Comment