2

foreword

Repository layer is required in the project? There seems to be no definite answer to this question. Here are my thoughts to share with you. If you don’t like it, don’t spray it.

Location of Repository

I understand that Repository is a big warehouse, which can contain MySQL , Redis , MongoDB ... and other data.

The developer who maintains this layer can be called warehouse administrator . When the user needs to query data, he needs to tell the warehouse administrator and the warehouse administrator will give it to him. As for where the warehouse administrator gets the data, The user does not need to be concerned.

Similarly, when you need to create or update data, you also need to tell the warehouse administrator to operate the data.

Summary: Repository mainly encapsulates the logic of data query, creation, update, deletion, etc. for users to call.

Implementation of Repository

  • Configurable conditional query
  • Configurable data transformation
  • Configurable data validation

Explain "configurable data conversion": when we need to return privacy fields, such as mobile phone number, if the user does not have data permission, the middle 4 digits of the mobile phone number field need to be processed with *, and the time for processing the return format etc.

If you are using the Laravel framework, you can refer to andersao/l5-repository

Repository's interface

Repository the interface layer can be understood as a contract (to learn under Laravel Contracts directory), it is subject to Domain driven, Repository defined function to reflect Domain intent and constraints. Domain I will provide what I need, and I will not provide what I don't need.

For example, the interface name can be defined as searchUsersById , searchUsersByName , but cannot be defined as searchUsersByInfo , and the query field is not recommended to be set to * , and only the required fields are queried and returned.

What is Domain ? Can be understood as the domain layer.

summary

Use Repository layer pros and cons, the drawbacks is somewhat cumbersome, not ORM smooth a shuttle. Of course, there are many advantages, mainly because the maintainability in the later stage is greatly improved.

To name some advantages:

  • When replacing and upgrading the ORM engine, the business logic is not affected;
  • To facilitate unit testing, Mock objects can be used instead of actual database access;

The above, I hope to help you.

Recommended reading


程序员新亮
2.9k 声望1.2k 粉丝

GitHub 9K+ Star,其中适合 Go 新手的开箱即用项目 go-gin-api 5.2K Star:[链接],联系我:wx-xinliang


引用和评论

0 条评论