laravel - 如何在 Laravel 中提出存储库请求?
问题描述
我在 laravel 中使用存储库模式从表中获取记录,但出现错误
“目标 [App\Repositories\ThirdPartyRepository] 在构建 [App\Http\Controllers\Dashboardcontroller] 时不可实例化。”
这是我的以下结构
app ->
Repositories
->Thirdpartyrepository.php
-> Thirdpartyrepositoryinterface.php
-> ThirdpartyServiceProvider.php
第三方存储库接口.php
namespace App\Repositories;
interface ThirdpartyRepositoryInterface
{
public function getAll();
}
第三方存储库.php
namespace App\Repositories;
abstract class ThirdPartyRepository implements ThirdpartyRepositoryInterface
{
public function getAll(){
$getcmp= DB::table('xyz')
->orderBy('id', 'desc')
->select('name', 'id', 'created_at')
->get();
return $getcmp;
}
}
第三方服务提供者.php
namespace App\Repositories;
use Illuminate\Support\ServiceProvider;
class ThirdpartyServiceProvider extends ServiceProvider
{
public function register(){
$this->app->bind(
'App\Repositories\ThirdpartyRepositoryInterface',
'App\Repositories\ThirdPartyRepository'
);
}
}
仪表板控制器.php
use App\Repositories\ThirdPartyRepository;
protected $thirdparty;
public function __construct(ThirdPartyRepository $thirdparty){
$this->thirdparty= $thirdparty;
}
public function getproducts(){
$getCompanies=$this->thirdparty->getAll();
dd ($getCompanies);
}
解决方案
为了详细解释我的评论,在您的仪表板控制器中,您正在注入实现而不是接口。您当前的代码:
public function __construct(ThirdPartyRepository $thirdparty){
$this->thirdparty= $thirdparty;
}
使用接口的主要优点是它允许您抽象代码。由于您正在注入实现,因此失去了这种优势。比如说,当你编写一个新的实现时,你需要改变这个控制器。应尽可能关闭类以进行修改(SOLID 原则)。
您需要将该方法更改为:
public function __construct(Thirdpartyrepositoryinterface $thirdparty){ //inject interface
$this->thirdparty= $thirdparty;
}
我的第三条评论:你应该有一个实现接口的普通类,而不是抽象类。
class ThirdPartyRepository implements ThirdpartyRepositoryInterface //remove abstract
{
public function getAll(){
并且您需要将您的服务提供者添加到 config.php 中的 providers 数组中。
'providers' => [
...
App\Providers\ThirdpartyServiceProvider::class, //your new service provider.
],
推荐阅读
- email - 撤消选择退出的安全方法
- java - Java,使类不可变
- maven - 如何在 Maven 项目中读取属性文件?
- python - 使用 Python 为类别动态分配权重
- android - 如何在 Android Studio 中更改完成背景
- python - Matplotlib 条形图_得到意外的图表
- ios - 在 Swift 中按顺序执行任务
- git - git make branch 镜像一个不同的分支
- javascript - 装饰器功能不起作用(意外令牌)
- php - 我无法让 imagemagick 在非线程安全的 Windows Server 2016 上的 PHP 中工作