


How to write elegant and attractive PHP code? A brief discussion on writing standards
How to write elegant and attractive PHP code? This article will take you through the basic writing specifications and framework specifications of PHP code. Understanding them will make your PHP code more elegant!
Introduction
Today Lao Wang told me that his code is so bad, like a lump of xiang. Ask me how to
improve the quality of my code and make my code more pleasing to the eye and more comfortable, just like the way
my eyes light up when I see a long-legged girl.
So I: You do this first, then this, and then that. . . . . .
Classmate Lao Wang: Stop making trouble, what exactly is going on?
Okay, I'm going to start pretending to be 13. . .
Basic specifications
Let’s talk about the most basic things first:
Variables Use camelCase for names. Don’t use pinyin for words you don’t understand. Instead, look up the dictionary to find the corresponding word.
Constant names should be named with uppercase letters and underscores. For example:
SYSTEM_EROOR = 50000
.Use the Tab key for indentation, do not type a bunch of spaces for indentation.
The class name is named in camel case with the first letter in capital letters. You need to know the meaning by seeing the name. Comments explain the function of this class. For example:
- The method name is named in camel case. The number of method lines should be controlled to about 80 lines. Comments should explain what the function is used for.
- The curly braces occupy one line, for example:
- ##foreach Use quotes with caution. For example, the following code will have problems:
2 4 6, the actual result is
2 4 4, as to why
Take a look at my previous article: Do you really understand the
& symbol in PHP?
. You can use the array_walk` method to avoid this problem, example:
- Avoid
- if
,
elesenesting If it is too deep, many nestings can be eliminated by early termination. Here is a simple example:
- Multiple
if/else
plug-in inuse switch instead, PHP8.0 version can use
matchto be more concise. Install the
SonarLint phpstorm
. If there are dotted lines in the code you write, it means it is not ideal, then you can modify it according to the prompts. I believe students with obsessive-compulsive disorder will definitely change it, and over time the code will become very standardized. For example:
Framework specification
- The above mentioned things are relatively basic, and the following is the main content.
- I believe many students have used one of the popular frameworks such as
thinkphp
丶
laravel丶
yii.
- These frameworks are all based on MVC architecture. I have seen many people’s codes and either write business logic in the controller or in the Model. Writing in the Model is better than writing in the Model. The one inside the controller is relatively better. In fact, it is not very friendly to large-scale projects.
- The following uses the Laravel framework as an example.
Parameter verification
- API requires parameter verification, but where is the most elegant way to write parameter verification? Many people may define rules in the controller and then call the verification method. Then the verification code will appear in every API, such as what my colleague wrote.
- This code will appear once in each API. Isn’t it very verbose? So how to solve it?
- Create a
Requsts
directory in Laravel's http directory to store the requested parameter verification class. Create aBaseRequest
class:
For example, login requires parameter verification and then create a LoginRequest
class to inherit this BaseRequest
.
- #When using it, just inject this request class into the Controller method.
#When the request parameters are obtained here, the form will be verified. Otherwise, if the parameter verification fails, the method just defined by the Request accumulation will be called to throw a Json exception and return the information to the customer. end.
Controller
The main workload of the controller is to obtain the request data and return content. It should not do more things, so you can define a Service layer to handle the business. logic. So my controller has only one line of code.
- Create a Services folder in Laravel's app directory to store the Service class, and create a BaseService class:
Then Create a UserService to handle user-related business logic.
Inject this UserService into UserController using:
Model
Model does not recommend writing business logic. Model is mainly used to define some content and should not manipulate data.
Model's data manipulation should be placed in the Repository, and create a folder Repositories
in Laravel's app directory.
Define BaseRepository:
Define UserRepository for user data related operations, inject UserModel in the constructor:
Constant
How to define many constants in the project?
Create a Constant directory in the app directory, and then create a Constant class to save these custom constants.
The advantage of this is:
- Custom constants can be managed centrally.
- When modifying the constant value, you only need to find and modify it once in this class. The code update is easy to maintain.
Original address: https://juejin.cn/post/6957290009682509854
Author: ClassmateLin
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to write elegant and attractive PHP code? A brief discussion on writing standards. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
