前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >大部分人的仓库模式都用错了吗?—— laravel

大部分人的仓库模式都用错了吗?—— laravel

原创
作者头像
windseeker
修改2023-11-09 18:57:25
1.8K0
修改2023-11-09 18:57:25
举报

什么是仓库模式(The Repository Pattern)?

Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. The business logic should be agnostic to the type of data that comprises the data source layer. (…) The repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source or Web service. —  mdsn.microsoft.com

简单来说, 仓库模式就是一种存放数据访问逻辑的容器, 它向业务层屏蔽了数据访问逻辑的细节, 在不清楚数据层设计结构的情况下, 我们也能按照业务逻辑来访问数据层。

如图:

Repository Pattern
Repository Pattern

可能你会疑问,检索数据并映射到实体模型,这不是 Eloquent 做的吗?Eloquent 的功能确实如此,但它不是仓库模式,而是 ORM(Object-Relational Mapper),它只是让我们以面向对象的方式访问数据库更容易,通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。

一些仓库模式的问题

我看过很多文章中仓库模式是这么实现的:

代码语言:txt
复制
<?php
namespace App\Repositories;

class EloquentUserRepository implements UserRepository {
    public function getAllUsers() {
        return $this->model->all();
    }
    public function getUser($id) {
        return $this->model->find($id);
    }
}

这段代码有什么问题呢?第一个错误是:方法的命名。因为我们已知我们需要访问的就是userRepository,所以方法中永远不应该存在user这样的关键字。更好的方式是:

代码语言:txt
复制
$userRepository->all();
$userRepository->find($id);

因为这些文章的误导,开发者可能会认为可以添加一个类似于这样的方法:

代码语言:txt
复制
public function getAdults()
{
    $users = $this->model->where("age", >=, 18)->get();
    return $users;
}

这是错误的,因为它只实现了业务逻辑,与数据库本身无关,不符合仓库模式的设计哲学。

上述代码还有一个错误是:在仓库中返回 Eloquent 模型,这会使你的业务逻辑层跟 Eloquent 耦合。而且,一开始就建立仓库是没有意义的,它只是 Eloquent 查询的抽象,根据定义,ORM 抽象不是仓库模式。

那么,如果返回自定义的对象并且在上层逻辑中不再使用 Eloquent 呢?这种方式当然可以,但是这会让你不能使用 Laravel 中很多重要的功能。

这个仓库模式的例子只是一个简单的demo,还有一些更高级的实现是先写仓库的接口,然后实现这个接口,并注册到服务提供者,这种方式确实看起来更完美了,但是也更复杂了。

在 Laravel 中文官方文档中,推荐的最佳实践有说,“绝不 使用 Repository,因为我们不是在写 JAVA 代码,太多封装就成了「过度设计(Over Designed)」,极大降低了编码愉悦感,使用 MVC 够傻够简单”。他们也确实遵循了, learnku开源论坛的代码 中,没有使用仓库模式,但是也足够优雅,可读性丝毫不差。

Service层

可能有人会问,“那如果不使用仓库模式,怎么让 controllers 更瘦呢”?其实仔细想想,这是个伪命题。如果你是正确的使用了仓库模式,controllers 其实不会变得更瘦。因为 Repository 只不过是一个特定的持久化适配器,它不应该实现任何业务逻辑和应用程序逻辑。

要想 controllers 变瘦,应该使用 Service 层。

摘一段 quora 上的回答:

A “Service Layer” exists between the UI and the backend systems that store data and is in charge of managing the business rules of transforming and translating data between those two layers. — Cliff Gilley, Quora

Service 层位于表示层和数据库层之间,所以这是放置所有业务逻辑的地方。Laravel 应用中一般会包含以下4层:

  • UI
  • Controlle
  • Service
  • Database/Eloquent

一个简单的 service 可能长这样:

代码语言:txt
复制
class UserService
{
    protected $user;
    public function __construct(User $user)
    {
        $this->user = $user;
    }
    public function create(array $attributes)
    {
        $user = $this->user->newInstance();
        $user->fill($attributes)
        $user->save();
        return $user;
    }
}

在 controller 中依赖注入:

代码语言:txt
复制
class UserController extends Controlle
{
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }
    public function store(CreateUserRequest $request)
    {
        $user = $this->userService->create(
            $request->except(['_token'])
        );
        return redirect()->route('user.show', ['id' => $user->id]);
    }
}

假设,之后如果加了一个需求,用户年龄小于18岁,将用户的 status 字段变成0。

如果你是将这段业务逻辑放在 repository 中,那么就打破了 repository 中不能实现业务逻辑的规则了。但如果你用的是 Service,那只需要改变 UserService 中的 create 方法即可:

代码语言:txt
复制
public function create(array $attributes)
{
    $user = $this->user->newInstance();
    if($attributes->age < 18) {
        $attributes->status = 0;
    }   
    $user->fill($attributes)
    $user->save();
    return $user;
}

当然,之前的 getAdults 方法也能放在 UserService 里面。

总结

如果是一些简单的应用,service 层甚至也可以不需要,查询逻辑放在 Model 中就好了。还可以利用 Trait 来精简逻辑代码量,提高可读性。

如果项目比较复杂,那么service 层是必须的,如果你仍然要引入 repository, 比如 l5-repository,那么推荐这样使用:

代码语言:txt
复制
public function getAdults() {
    $users = $this->userRepo->where('age', >=, 18)->get();
    return $users;
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是仓库模式(The Repository Pattern)?
  • 一些仓库模式的问题
  • Service层
  • 总结
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档