【发布时间】:2022-10-16 16:27:47
【问题描述】:
窥视,我迷路了。尝试了一切,在谷歌点击的第 10 页搜索了 5 个小时后,我放弃了。也许我只是不知道如何向谷歌询问正确的关键字..
我有这种情况:在流明应用程序中,我们称之为 X,我需要自定义包 CRUD 和存储,存储正在使用 CRUD 的功能。
StorageService 有:
use Crud\Services\BaseService;
class StorageService extends BaseService{}
Crud\BaseService 有构造函数,它使用模型:
use Illuminate\Database\Eloquent\Model;
class BaseService
{
protected $model;
public function __construct(Model $model)
{
$this->model = $model;
}
}
当我尝试对我的应用 X 执行任何操作时,我收到错误消息:
Target [Illuminate\Database\Eloquent\Model] is not instantiable while building [Lumee\Storage\Services\StorageService]
我无法理解如何获得适当的模型类,因为我看到模型是抽象类。
另外,我在另一个应用程序中成功使用了这个 CRUD 包,唯一的区别是,CRUD 是直接在应用程序中使用的,而不是通过其他一些包。我很困惑,为什么没有任何额外的绑定和服务注册就可以工作..
编辑:在 StorageServiceProvider 中添加了一些绑定(启动和注册方法):
$this->app->bind(BaseService::class, function(){
return new BaseService(new Model());
});
并在我的 bootstrap/app.php 中注册 Storage Service Provider:
$app->register(Storage\Providers\StorageServiceProvider::class);
事情仍然返回相同的错误。我尝试在 CrudServiceProvider 中绑定,不。
【问题讨论】:
-
您无法自动解析此
BaseService类,因为您已将其设置为依赖于无法实例化的Model...如果您想从容器中解析此 Service 类,则需要某种类型的绑定需要知道如何解决Model(也可以是扩展Model的任何内容) -
谢谢您的回答。我应该在哪个级别绑定它?我试图让我的代码尽可能少,我真的必须介绍 CrudServiceProvider 吗?我试过 $this->app->bind(BaseService::class, function(){ return new BaseService(new Model()); });在 StorageServiceProvider 中,也注册在 X->boostrap/app.php 中。
-
我在 OP 中编辑了一些附加信息
-
$this->app->bind(BaseService::class, ...) 在哪里添加在引导或注册中?
-
我尝试将它添加到这两个功能都无济于事。它们可以同时用于这两个功能吗?
标签: laravel eloquent lumen instantiation