Table of Contents
Indentation" >Indentation
PSR-3 Log Interface Specification" >PSR-3 Log Interface Specification
" >##PSR-4 automatic loading specification
Home Backend Development PHP Tutorial PSR specification of PHP specification

PSR specification of PHP specification

Apr 26, 2018 pm 02:42 PM
php blog

This article introduces the psr specification in the PHP specification. Now I share it with you. Interested friends can take a look.

Reference: http://psr .phphub.org/

PSR is not an official PHP standard, but a series of standards extracted from well-known PHP projects such as Zend and Symfony2 , there are currently more and more community projects joining and following this standard. <br>

<br>

<br>

  • #PSR- 0 Autoloading 2 Code style

  • PSR-3 log interface

  • PSR-4 How to specify the file Path to automatically load class definition

  • PSR-1 Basic Code Specification

This specification establishes relevant standards for basic elements of code to ensure a high level of technology among shared

PHP interoperability.

File

##·        PHPCode file

must

ends with or <span style="color:#858080;background:#F9FAFA;"></span>Start of tag;##·                                                                       Must<span style="color:#858080;background:#F9FAFA;"></span> with

without

BOM UTF-8 Encoding;<span style="color:#858080;background:#F9FAFA;"></span>·                                                       PHP<span style="color:#858080;background:#F9FAFA;"></span><span style="color:#858080;background:#F9FAFA;"></span><span style="color:#858080;background:#F9FAFA;"></span>

##Only define classes, functions, constants, etc.Statements, or others will produce Side effects Operations (such as: generating file output and modifying .ini Configuration files, etc.), you can only choose one of the two; <span style="color:#FF0000;background:#F9FAFA;"></span> Namespace and class

·        Class naming must follow <span style="color:#858080;background:#F9FAFA;">StudlyCaps</span> Camel case starting with capitalNaming convention;

##·        Each class is an independent file, and the namespace has at least one level: the top-level organization name (vendorname)

  • Class attribute: Lowercase starting camel case $studlyCaps<span style="color:#858080;background:#F9FAFA;"></span>

  • Class method: lowercase beginning with camel case

##Constant

##·       

Constants in the class have all letters must is in uppercase letters, and words are separated by underscores;

    Method name
  • must

    conform to camelCase style naming convention of camel case starting with lowercase. <span style="color:#858080;background:#F9FAFA;"></span>

##PSR-2 Coding Style Specification

Indentation

##·                                                                    You must use

4 spaces instead of "Tab keys ” to indent. Lines The number of characters per line should be softly maintained at 80

Within , there must not be more than 120, but there must not be a hard limit.

  • All

    PHP filesmustbegin with a blank line

    As an end.
  • Each line must be cannotThere must be more than one statement

  • After each

    namespace namespace declaration statement and use declaration block, a blank line must be inserted.

  • ##The opening brace ({) of class must be written after the function declaration on its own line , the closing curly brace (}) must also be written after the function body on its own line

    .
  • The opening curly brace ({) of the method must be written after the function declaration is on its own line , and the closing brace Brackets (}) must also be written after the function body on its own line .

  • The opening brace ({) of the control structure must be written on the same line as the declaration, and the closing curly brace (}) must be written after the body on its own line .

##Modifier

  • Class properties and methods must add access modifiers (private,protected and public), abstract and final must be declared before access modifiers, while static must is declared after the access modifier.

##Space

  • Class method parametersAfter each commamustThere must be a space, and the comma There must be no spaces in front

  • There must be no spaces after the opening left bracket and before the closing right bracket of the control structure.

    There must be no spaces.

Keywords

##·      

Control structure There must be a space character after the keyword , but when calling a method or function, there must be no . All PHP keywords must be all lowercase, and the constants true, false, and null must also be all lowercase.

  • PSR-3 Log Interface Specification

    <span style="color:#858080;background:#F9FAFA;">#LoggerInterface</span> The interface is defined externally Eight methods are used to record the eight levels of logs defined in RFC 5424 : debug info notice warning error, critical, alert and emergency .

    The ninth method——log, its first parameter is Recorded level. This method can be called using a predefined level constant as a parameter, must has the same effect as directly calling the above eight methods. If the level constant parameter passed in is not predefined, must throwsPsr\Log\InvalidArgumentException type of exception. In cases of uncertainty, users should not use unsupported level constants to call this method.

    ##/**

    * Log level constant definition

    */

    ##class LogLevel

    ##{

    constEMERGENCY ='emergency';

    ##constALERT='alert';

    constCRITICAL ='critical';

    constERROR ='error';

    constWARNING ='warning';

    constNOTICE = 'notice';

    constINFO     ='info';

           constDEBUG='debug';

    }

    ##PSR-4 automatic loading specification

    Similar to the following example: ()*

    # #1. Fully compliant class names must have a top-level namespace (Vendor Name)

    2. Fully compliant class names can have multiple sub-namespaces

    3. Completely Compliant class names should have a terminating class name

    4. Underscores have no special meaning in fully compliant class names

    5. Letters can be any combination of upper and lower case in fully compliant class names

    6. All class names must be quoted in a case-sensitive manner

    7. The termination class name corresponds to a file ending with .php . The file name must match the case of the terminating class name

    Some common customization specifications

    Control layer

    1. No sql statement appears (sql is encapsulated into the model layer and then called as a method)

    2. sql statement, 3 or more lines of logical code, blank lines

    3. No blank lines between contextual functions or methods

    4. Bool uses if (true === $name) in the form

    5. Use double quotes to link variables

    6. Pay attention to implicit conversion

    7. When using global variables, you need to comment on their meaning. The value range is

    ##/** * Overall description of global variables<br> * Global STATUS_CODE * 0 -SUCCESS<br> * 2-ERROR<br>*/<br>STATUS_CODE<br><br>

    8. The function header has the following comments:

    /*************************************************<br> Function: // Chinese name of function<br>Description: // Description of function functions, performance, etc.<br>Calls: // List of functions called by this function<br>Called By: // List of functions that call this function <br>Table Accessed: // The accessed table (this item is only for programs involving database operations) <br>Table Updated: // The modified table (this item is only for programs involving database operations) Program to operate on the database) <br>Input:                           // Input parameter description, including the role of each parameter, value description and the relationship between parameters. <br>Output:                // Description of the output parameters. <br>Return:                                                                                                                                                                                                                                                                                                   ## ***********************/<br><br>

    9. Comments Blank lines

    // code one comments<br>program code one <br><br> // code two comments<br>program code two

    ##10. File header comments

    ##/***************************************************** ********

    Copyright (C), 1988-1999, Huawei Tech. Co., Ltd. // CopyrightFileName: test.cpp                                           File name<br>Author:                                                                                                                                                                                                                                                                    Description:                                                                         Main functions and their functionsHistory:                                                                                                                                                                                                                                                          ​        init<br> ********** ****************************************************/<br><br><br><br> <br><br><br><br>11. The case jump of the switch statement requires comments <br>

    12. Naming of marked variables:

    temp can be abbreviated as tmp ;<br>flag can be abbreviated to flg ;<br>##statistic can be abbreviated to stat ;<br>increment can be abbreviated as inc ;<br>message Can be abbreviated as msg ;

    ##13. Naming prefix of the interface

    add / remove                                                                                                                     ##end           create / destroyinsert /<br>delete first / last get / releaseincrement /<br>decrement put / getadd /<br>delete lock / unlock open / closemin /##max old <br>/ new        start / stopnext /previous      source <br> / target show / hidesend /receive source <br>/ destinationcut / paste up <br>/ down ##14. Try to use constants for status codes instead of hard-to-understand numbers

    should be changed to the following form. <br>#defineTRUNK_IDLE 0<br>#define TRUNK_BUSY 1<br> <br>if (Trunk[index].trunk_state == TRUNK_IDLE)<br>{<br>   Trunk [index].trunk_state = TRUNK_BUSY;<br> ... //program code<br>}

    15. Class file names use first capital camel case, Ordinary files are named using underline format

    16. Variables in the configuration are named using underline format

    ##

    1. 变量自增自减写到表达式前面: --e >= $name
    Copy after login
    2. 程序顺序应该遵循:参数定义代码->判断逻辑代码->业务逻辑代码
    Copy after login
    3. 大的数据使用引用
    Copy after login
    4. 为逻辑代码里每个复杂度高/重复度高的代码添加注释
    Copy after login
    5. 尽量不为简短代码引入新的变量,减少变量污染
    Copy after login
    <br>
    Copy after login

    ##1. If you can define the class method as static, try to define it as static, its speed will increase nearly 4 times.

    2, The speed of $row['id'] is $row[id] of 7 times.

    ##3##、 echo is faster than print, and uses echo's multiple parameters(Translation Note: Refers to Commas instead of periods ) instead of string concatenation, like echo $str1 ,$str2.

    ##4##, executing for Determine the maximum number of loops before looping. Do not calculate the maximum value every loop. It is best to use foreach replace. ##5

    ##. Unregister those unused variables, especially large arrays, for release Memory.

    6, try to avoid using __get, __set##, __autoload .

    ##7##、 require_once()#is expensive.

    8, Try to use absolute paths when including files, because it avoids PHP The speed of finding files in include_path will take less time to parse the operating system path.

    ##9##, If you want to know when the script starts executing(Translation Note: The server receives the client request )# At the ## moment, it is better to use $_SERVER['REQUEST_TIME'] than time().

    10

    , function replaces regular expression to complete the same function. ##11

    ##、## The str_replace function is faster than the preg_replace function, # The efficiency of the ##str function is four times that of the str_replace function times. 12

    , if a string replacement function, accepts arrays or characters As a parameter, and the length of the parameter is not too long, you can consider writing an additional piece of replacement code so that each parameter passed is one character, instead of just writing a line of code to accept an array as a parameter for query and replacement.

    ##13, use the selective branch statement

    (Translation Note: switch case) is better to use Multiple if,##else if Statement. ##14##, use

    @

    #The practice of blocking error messages is very inefficient, extremely inefficient. ##15##, open ## The

    mod_deflate module of #apache## can improve the browsing speed of web pages.

    16. The database connection should be closed when finished using it. Do not use long connections.

    17##, Error messages are expensive.

    ##18##、AvoidincrementGlobal VariableRelated recommendations:

    About PSR-4 of PHP specification About Lei Feng’s handwritten newspaper About the Spring Festival Handwritten newspaper about the Spring Festival Ancient

    PHP specification PSR-1 php language php manual php development engineer

    The above is the detailed content of PSR specification of PHP specification. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles