How to Write Less PHP “Bad” Code

  Doophp, laravel, php

图片描述

It is written to the children’s shoes of newborn calves who are not afraid of tigers. Big brothers can pick it at will.
This chapter is based on PHP Laravel

Actual combat coursehttps://segmentfault.com/a/11 …

Preface

People often ask

  • How to design the catalogue better?
  • How is the code well distributed?
  • How to write a maintainable project?

I haven’t written less about the “rotten” project either. The following is a summary of the articles and personal development experiences of Internet leaders.

Controller

clipboard.png

As the name implies, the Controller is a Controller. When you started PHP, you knew that the controller represents the C layer in MVC. The concept of MVC itself is code separation. It teaches you how to separate business. However, with the continuous development of business, the complexity of code also increases. The links between functions and functions are complicated. Finally, your MVC becomes the following figure. Therefore, relying on the design idea of MVC alone cannot support the continuous development of business.

Now we redefine the Controller’s tasks and capabilities. The controller only controls Http Reqeust’s requests, thus conforming to the SOLID single function principle.

clipboard.png

Writing business code directly in the Controller will make the code cumbersome and not easy to maintain and expand.

<?  php
 namespace App\Http\Controller;
 
 class UserController extends Controller{
 
 public function register(Request $request){
 $user = new User();
 $user->username = $request->input('username');
 $user->password = $request->input('password');
 $result = $user->save();
 
 return $result;
 }
 
 }

At this time, we should think about how to separate the business code. We introduce the concept of Service.

Service

Service itself translates into service.

  • Inject external methods and public methods into Service
  • Inject Service into Controller

clipboard.png
Like the picture above

UserController

<?  php
 namespace App\Http\Controller;
 
 class UserController extends Controller{
 
 public $request;
 
 protected $userService;
 
 public function __construct(Request $request, UserService $userService)
 {
 $this->request = $request;
 
 $this->userService = $userService;
 }
 
 public function register()
 {
 //... validation
 return $this->userService->register ($this->request->all());
 }
 
 }

UserService

<?  php
 namespace App\Service;
 
 class UserService{
 
 public function register($data)
 {
 $username = $data['username'];
 $password = $data['password'];
 
 $password = encrypt ($password);
 
 $user = new User();
 $user->username = $username;
 $user->password = $password;
 $result = $user->save();
 
 return $result;
 }
 
 }

So far, we have at least completely separated the business from the request. However, it is still not satisfactory. If all the businesses and CURD are written in the Service, it will only transfer the Controller’s overstaffing to the Service, and then the Service will have no meaning.
Therefore, we need to continue to divide the Service and separate the r operation on the database, because the operation of CUD is basically the same, while the r operation is colorful according to the complexity of the service. So independent r operation. At this time we quoted the concept of Repository.

Repository

We use Repository to assist the Model and encapsulate the relevant query logic into different repositories, which is convenient for the maintenance of logic codes.

  • Consistent with SOLID’s Single Principle
  • SOLID-compliant dependency reversal

clipboard.png

UserController

<?  php
 namespace App\Http\Controller;
 
 class UserController extends Controller{
 
 public $request;
 
 protected $userService;
 
 public function __construct(Request $request, UserService $userService)
 {
 $this->request = $request;
 
 $this->userService = $userService;
 }
 
 public function getUserInfo()
 {
 //... validation
 return $this->userService->getUserInfo ($this->request->all());
 }
 
 }

UserService

<?  php
 namespace App\Service;
 
 class UserService{
 public $userRepository;
 
 public function __construct(UserRepository $userRepository){
 $this->userRepository = $userRepository;
 }
 public function getUserInfo()
 {
 return $this->userRepository->getUserInfo($data);
 }
 
 }

UserRepository

<?  php
 namespace App\Repository;
 
 class UserRepository{
 
 public function getUserInfo($data)
 {
 $userId = $data['user_id'];
 $result = User::where('id',$userId)->first();
 
 return $result;
 }
 
 }

After solving the problem of R, someone asked, can CUD be put together because it is relatively unified and simple? The answer is NO, we quote a new noun Action.

Action

This is what I learned after reading @Charlie_Jade’s article.

Separate each operation file, e.g. createuser, deleteuser, updeuser

  • Consistent with SOLID’s Single Principle

clipboard.png

UserController

<?  php
 namespace App\Http\Controller;
 
 class UserController extends Controller{
 
 public $request;
 
 protected $userService;
 
 public function __construct(Request $request, UserService $userService)
 {
 $this->request = $request;
 
 $this->userService = $userService;
 }
 
 public function register(){
 //... validation
 return $this->userService->register($this->request->all());
 }
 
 public function getUserInfo()
 {
 return $this->userService->getUserInfo ($this->request->all());
 }
 
 }

UserService

<?  php
 namespace App\Service;
 
 class UserService{
 
 public function getUserInfo(UserRepository $userRepository)
 {
 return $this->userRepository->getUserInfo($data);
 }
 
 public function register(){
 $result = (new CreateUser())->execute($this->request->all());
 
 return $result;
 }
 
 }

UserRepository

<?  php
 namespace App\Repository;
 
 class UserRepository{
 
 public function getUserInfo($data)
 {
 $userId = $data['user_id'];
 $result = User::where('id',$userId)->first();
 
 return $result;
 }
 
 }

CreateUser

<?  php
 
 namespace App\Action;
 
 use App\Model\Member;
 
 class CreateUser extends CreateUserWallet
 {
 public function execute(array $data)
 {
 $models           = new Member();
 $models->tel      = $data['tel'];
 $models->password = $data['password'];
 $result           = $models->save ();
 
 return $result;
 }
 }

The above code logic is shown in the following figure
clipboard.png
In addition to HTML,JS, etc. such as template (V), some other rules, or methods, are needed to decouple some codes. Code cases are not provided below.

Common

In the process of partial development, you may need some public methods (not public classes, such as email, etc. it is not appropriate to use them), such as inquiring about the user’s balance, whether the user is registered or online, generating an order number, etc. It is easier to use Common. He looks more like a public library

clipboard.png

Event

You can choose to use it when you don’t care about the execution result, but the Event’s Listen also provides a queue.

Exception

Don’t use Return to return all your error prompts. Most of the time your return is not necessarily your return.

Thank you

Thank you for reading this article. If you have any new ideas, please discuss them in the comment section.

Reference article

Laravel’s Medium and Large Project Architecture:http://oomusou.io/laravel/arc …
Laravel program architecture design ideas use action classes:https://segmentfault.com/a/11 …
How to use Service mode? :http://oomusou.io/laravel/ser …
SOLID principle of object-oriented design:https://www.cnblogs.com/shany …