You need to enable JavaScript to run this app. Laravel如何实现单存储库的Repository设计模式 避免重复代码
优惠活动
大模型
产品
解决方案
定价
更多

Laravel如何实现单存储库的Repository设计模式 避免重复代码

Laravel Repository 模式通用方法封装方案

1. 第一步:定义通用基础接口

首先创建所有Repository共用的基础接口,把通用方法统一声明在这里:

// app/Repositories/BaseRepositoryInterface.php
namespace App\Repositories;

interface BaseRepositoryInterface
{
    public function get($id);
    public function all();
    public function add(array $data);
    public function update($id, array $data);
    public function delete($id);
}

2. 第二步:实现抽象基础Repository类

创建抽象类实现基础接口的所有通用方法,通过构造函数接收对应Model实例:

// app/Repositories/BaseRepository.php
namespace App\Repositories;

use Illuminate\Database\Eloquent\Model;

abstract class BaseRepository implements BaseRepositoryInterface
{
    protected $model;

    // 构造函数注入对应Model
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    public function get($id)
    {
        return $this->model->find($id);
    }

    public function all()
    {
        return $this->model->all();
    }

    public function add(array $data)
    {
        return $this->model->create($data);
    }

    public function update($id, array $data)
    {
        $record = $this->get($id);
        $record?->update($data);
        return $record;
    }

    public function delete($id)
    {
        return $this->model->destroy($id);
    }
}

3. 第三步:修改具体Repository的实现

3.1 具体业务接口定义

如果有业务自定义方法,就在对应业务接口里声明,没有的话直接继承基础接口即可:

// app/Repositories/PostRepositoryInterface.php
namespace App\Repositories;

interface PostRepositoryInterface extends BaseRepositoryInterface
{
    // 这里只需要写Post特有的方法,通用方法已经继承
    public function getPublishedPosts();
}

3.2 具体Repository类实现

继承基础抽象类,只需要实现自己特有的方法,通用方法不需要重复编写:

// app/Repositories/PostRepository.php
namespace App\Repositories;

use App\Models\Post;

class PostRepository extends BaseRepository implements PostRepositoryInterface
{
    // 构造函数直接传入当前Model到父类
    public function __construct(Post $model)
    {
        parent::__construct($model);
    }

    // 只实现Post特有的方法即可
    public function getPublishedPosts()
    {
        return $this->model->where('status', 'published')->get();
    }
}

4. 原有调用逻辑无需修改

控制器调用、服务提供者绑定的逻辑和之前完全一致,不需要调整:

// 控制器示例
namespace App\Http\Controllers;

use App\Repositories\PostRepositoryInterface;

class PostController extends Controller
{
    protected $post;
    public function __construct(PostRepositoryInterface $post)
    {
        $this->post = $post;
    }
    public function index()
    {
        $data = [
            'posts' => $this->post->all()
        ];
        return $data;
    }
}

优化建议

如果不想每次新增Repository都手动绑定接口和实现,可以在RepositoryServiceProvider里写自动绑定逻辑,通过文件名匹配自动绑定,减少配置代码。


内容的提问来源于stack exchange,提问作者PHP User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 16:57:02