search
HomeBackend DevelopmentPHP TutorialHow to write high-quality PHP code

How to write high-quality PHP code

Jun 18, 2020 pm 05:08 PM
laravelmvcphprear end

How to write high-quality PHP code

Written for those newborn calves who are not afraid of tigers, you can read it at will. This chapter is based on PHP Laravel

Preface

People often ask

  • How to design a directory better?
  • How to distribute the code well?
  • How to write a maintainable project?

I also write about "bad" projects. The following is based on the summary of articles and personal development experience of major Internet experts.

Controller

How to write high-quality PHP code

Controller, as the name suggests, is a controller. When you get started with PHP, you know that Controller represents the C layer in MVC. The concept of MVC itself is code separation, which teaches you how to separate businesses. However, as the business continues to develop, the complexity of the code also increases, and the links between functions are intricate. In the end, your MVC becomes As shown in the figure below, relying solely on the MVC design idea can no longer support the growing business.

Now we redefine the tasks and capabilities of the Controller. The controller only controls Http Reqeust requests, which complies with the SOLID single function principle.

How to write high-quality PHP code

Writing business code directly in the Controller will make the code extremely bloated and difficult 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, and we introduce the concept of Service

Service

Service itself is translated as service

  • Inject external methods and public methods into Service
  • Inject Service into the controller
How to write high-quality PHP code

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[&#39;username&#39;];            $password = $data[&#39;password&#39;];         
			$password = encrypt ($password);			
			$user = new User();			$user->username = $username;			$user->password = $password;			$result = $user->save();			return $result;
		}

    }复制代码

Until now , we at least completely separate the business from the requests. But it is still unsatisfactory. If all business and CURD are written in Service, it will just transfer the bloat of Controller to Service, and then Service will have no meaning in existence. Therefore, we need to continue to divide the Service and separate the R operations of the database, because the operations of CUD are basically the same, while the R operations become more colorful according to the complexity of the business. So standalone R operation. At this time we refer to the concept of Repository.

Repository

We use Repository auxiliary Model to encapsulate relevant query logic into different repositories to facilitate the maintenance of logic code

  • Conforms to the single principle of SOLID
  • SOLID-compliant dependency inversion
How to write high-quality PHP code
##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[&#39;user_id&#39;];            $result = User::where(&#39;id&#39;,$userId)->first();			
			return $result;
		}

    }复制代码

After solving the problem of R, someone asked, can it be put together because CUD 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

Independent of each operation file, such as CreateUser, DeleteUser, UpdateUser

    Conform to the single principle of SOLID
How to write high-quality PHP code
##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[&#39;user_id&#39;];            $result = User::where(&#39;id&#39;,$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 figure below

How to write high-quality PHP code
##Except template (V) For HTML, JS, etc., some other rules or methods are needed to achieve decoupling of some codes. No code examples are provided below.

Common

is translated as public, commonly used. In some development, you may need some public methods (non-public classes, such as email sending, etc., it is not appropriate to use them), such as query User balance, query whether the user is registered or online, generate order number, etc. Using Common is even simpler. It is more like a public function library

How to write high-quality PHP code

Event

You can choose to use it when you don’t care about the execution results, but the Listen of Event Queues are also provided.

Exception

Don’t use Return to return all your error messages. In many cases, your return may not be your return

Thank you

Thank you all After reading this article, if you have any new ideas, please feel free to discuss them in the comment area.

Recommended tutorial: "php tutorial"

The above is the detailed content of How to write high-quality PHP code. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software