首页 > 解决方案 > 如何在 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);
        }

标签: laravel

解决方案


为了详细解释我的评论,在您的仪表板控制器中,您正在注入实现而不是接口。您当前的代码:

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.

],

推荐阅读