Laravel绑定接口后仍提示IUploadsRepository无法实例化如何解决
问题根源
你报错的直接原因是将UploadsRepository声明为了abstract抽象类,Laravel服务容器无法对抽象类进行实例化,哪怕你已经做了接口和实现类的绑定,也无法完成依赖注入,就会抛出Target [xxx] is not instantiable的异常。
IDE飘红的原因也很好解决:你只实现了RepositoryInterface接口,但没有继承prettus/laravel-repository扩展包提供的BaseRepository基类,这个基类已经默认实现了RepositoryInterface里的所有通用方法,你不需要自己逐个实现,也不需要把类设为抽象。
修复步骤
- 修正
UploadsRepository.php代码,去掉abstract声明,继承BaseRepository,并指定对应的关联模型:
<?php namespace App\Dal\Repositories; use App\Dal\Interfaces\IUploadsRepository; use Prettus\Repository\Eloquent\BaseRepository; // 这里替换成你自己的Upload模型类路径 use App\Models\Upload; class UploadsRepository extends BaseRepository implements IUploadsRepository { // 指定当前仓库对应的数据模型 protected $model = Upload::class; /** * @return string */ public function getUploads(): string { return "test"; } }
如果还没有创建对应的Upload模型,先创建对应模型即可,否则BaseRepository初始化时还会报错。
- 清空Laravel配置缓存,避免旧绑定规则残留:
php artisan config:clear php artisan cache:clear
你原来的接口定义、服务提供者绑定、config/app.php的服务注册都没有问题,修改完成后重新请求就可以正常注入了。
内容的提问来源于stack exchange,提问作者sp92
相关产品推荐
相关产品推荐

