根据“binding-interfaces-to-implementations”,可以将接口(interface)与其实现绑定(bind),如下所示:
$this->app->bind(
'App\SharedContext\Userable',
'App\Modules\Core\User'
);
所以当我调用下一行时,我会得到一个 User
对象:👏💃$user = $this->app->make(Userable::class);
然而... 当我尝试使用 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');
}
显然,它给了我以下错误:😒⛔⛔⛔ Cannot instantiate interface App\SharedContext\Userable
如果我尝试按如下方式实例化接口(interface),则会出现相同的错误:$anInterfaceCannotBeInstantiateFool = new Userable();
我认为应该有一种方法可以委托(delegate)给抽象(接口(interface))而不是使用具体的类。通过这种方式,将应用程序模块化并使其更加解耦会容易得多。有没有人在 Laravel 中做过类似的事情?
最佳答案
我相信您可以通过放置在应用程序某处的静态函数调用来实现您想要的。
public static getClass () {
return get_class(resolve(Userable::class));
}
这将解决您的问题,因为您现在可以绑定(bind)该类并在运行时解决它。
关于php - 在 Eloquent 关系中将接口(interface)绑定(bind)到实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64086883/