Skip to content
Advertisement

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(
    'AppSharedContextUserable',
    'AppModulesCoreUser'
);

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 IlluminateDatabaseEloquentBuilder
 */
public function creatorUser()
{
    return $this->belongsTo(Userable::class, 'created_by');
}

it, obviously, gives me the following error: ????

⛔⛔⛔ Cannot instantiate interface AppSharedContextUserable

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement