php 仓库模式,仓库模式被误用了吗?—— laravel

什么是仓库模式(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

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

如图:

6b1a423ef669

Repository Pattern

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

一些仓库模式的问题

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

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这样的关键字。更好的方式是:

$userRepository->all();

$userRepository->find($id);

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

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

Controller

Service

Database/Eloquent

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

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 中依赖注入:

class UserController extends Controller

{

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 方法即可:

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,那么推荐这样使用:

public function getAdults() {

$users = $this->userRepo->where('age', >=, 18)->get();

return $users;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值