According to "binding-interfaces-to-implementations" it is possible to bind an interface with its implementation, as follows:
$this->app->bind(
'App\SharedContext\Userable',
'App\Modules\Core\User'
);
So when I call the next line, I will get an User
object: 👏💃
$user = $this->app->make(Userable::class);
However... when I try to do the same process with an Eloquent relationship:
/**
* Returns the user who created this... whatever. (I wish it worked! 🙄)
*
* @return Illuminate\Database\Eloquent\Builder
*/
public function creatorUser()
{
return $this->belongsTo(Userable::class, 'created_by');
}
it, obviously, gives me the following error: 😒
⛔⛔⛔ Cannot instantiate interface App\SharedContext\Userable
The same error if I try to instance an interface as follow:
$anInterfaceCannotBeInstantiateFool = new Userable();
I think there should be a way to delegate to an abstraction (interface) instead of using a concrete class. In this way it would be much easier to modularize the application and make it more decoupled.
I believe you can achieve what you want with a static function call, placed somewhere in your app.
public static getClass () {
return get_class(resolve(Userable::class));
}
This will solve your problem, as you can now bind the class and resolve it at run time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With