Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Interfaces to Implementations in Eloquent relationships

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.

Has anyone done something similar in Laravel?

like image 828
tomloprod Avatar asked Oct 15 '22 00:10

tomloprod


1 Answers

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.

like image 56
mrhn Avatar answered Oct 20 '22 18:10

mrhn