I'm quite new to this so pls bare with me. :)
I have 2 implementations of an interface, let's just name them BankService1
and BankService2
and both of them adheres to DisbursementInterface
.
Typically if I only need one implementation, i would just bind the interface and the implementation in bootstrap/app.php
and inject the interface to the constructor of the controller. However, I want to dynamically bind the implementation based on user input kind of like this:
//if remittance is true, use bank 1 else bank 2
$disbursementService = ($request['remittance'] ? 'BankService1' : 'BankService2');
$this->app->bind('My\Namespace\DisbursementInterface', "My\Namespace\\{$disbursementService}");
I think the middleware is the best place to do like this since i need the $request
object. However i'm having a hard time binding the implementations because like what i said, i'm still quite new at this.
Any suggestions?
I figured it out. All I actually need is to create a Service Container! I don't actually need it to be in the middleware at all.
class DisbursementServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(DisbursementInterface::class, function($app) {
if ($this->app->request->remittance) {
return new BankService1();
}
return new BankService2();
});
}
}
after that, I registered my service container in bootstrap/app.php
and now it works! I can now switch between implementations based on user input :)