将接口绑定到 Eloquent 关系中的实现

tom*_*rod 5 php module interface laravel eloquent

根据“ binding-interfaces-to-implementations ”,可以将接口与其实现绑定,如下所示:

$this->app->bind(
    'App\SharedContext\Userable',
    'App\Modules\Core\User'
);
Run Code Online (Sandbox Code Playgroud)

所以当我调用下一行时,我会得到一个User对象:

$user = $this->app->make(Userable::class);
Run Code Online (Sandbox Code Playgroud)

但是……当我尝试使用 Eloquent 关系执行相同的过程时:

/**
 * 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');
}
Run Code Online (Sandbox Code Playgroud)

这,显然,给了我以下错误:

??? Cannot instantiate interface App\SharedContext\Userable
Run Code Online (Sandbox Code Playgroud)

如果我尝试按如下方式实例化接口,则会出现相同的错误:

$anInterfaceCannotBeInstantiateFool = new Userable();
Run Code Online (Sandbox Code Playgroud)

我认为应该有一种方法可以委托给抽象(接口)而不是使用具体的类。通过这种方式,将应用程序模块化并使其更加解耦会容易得多。

有没有人在 Laravel 中做过类似的事情?

mrh*_*rhn 4

我相信您可以通过放置在应用程序中某处的静态函数调用来实现您想要的目的。

public static getClass () {
    return get_class(resolve(Userable::class));
}
Run Code Online (Sandbox Code Playgroud)

这将解决您的问题,因为您现在可以绑定该类并在运行时解决它。