One person agreed with the article

PSR is short for PHP Standards Recommendation, which stands for PHP Standards Recommendation. To understand PSR, it is important to know the person/organization who developed the standard ———— php-fig.

PHP-FIG

Php-fig, which stands for PHP Framework Interop Group, is an organization made up of representatives of PHP frameworks who get together to “discuss common features between frameworks and find ways to work together.” Php-fig develops recommended specifications that PHP frameworks can voluntarily implement to improve communication and sharing capabilities of other frameworks. The mission of PHP-FIG is to achieve interoperability between frameworks.

Psr-1: Basic code style

PSR is the PHP standard, and PSR-1 is the most basic and simplest standard for PHP.

PHP tags

The code must be placed in
or
in the tag. No other tag syntax is allowed

Many PHPer’s are easy to follow, and in the real world they use normal
tag

coding

All PHP files must use UTF-8 character set encoding and must not have Byte Order Mark (BOM)

This is also very common, that is, there is no BOM format and there is BOM format. I remember that when I first typed PHP code, my predecessors always asked me to use IDE to change it to no BOM format. I was ignorant at that time, so I followed it. The BOM produces extra output, like an extra blank line:

There are some errors in PHP handling BOM headers, which may result in the output of the file when using a header or session_start function, mostly because the BOM header was sent out. Because from PHP’s point of view, it becomes a space. So use BOM free format

purpose

A PHP file can define symbols (classes, traits, functions, constants, etc.) or perform side effects (produce results or process data), but it cannot do both at once

This regulation basically means that a variable, method or class can only perform one operation or one thing correspondingly, which ensures that the code is clear and easy to understand, and also ensures that methods and variables are single and do their respective jobs. In fact, for the sake of convenience, we can decouple well in the future when the project/application is larger

Automatic loading

PHP namespaces and classes must comply with the PSR-4 autoloader standard

See the detailed explanation of PSR-4 later

The name of the class

PHP class names must be humped, aka header

Girl_friend, girl_friend, girl_friend, girl_friend, girl_friend, girl_friend, girl_friend, girl_friend, girl_friend I remember that the CI2 project of the company used this participle, but it was also a framework regulation. Later in my own project, I had a hunch that I used the hump. Haha, praise for my vision ~

Name of constant

PHP constant names must be capitalized;

This should go without saying, since it was ingrained when YOU first started writing PHP.

Method name

We’re going to use camelback.

Methods are named similarly to classes, but there are some differences: the class is named in uppercase (BoyFriendMoney) and the method is named in lowercase (BoyFriendMoney)

Psr-2: Strict code style

Psr-2 is a stricter code specification than PSR-1. Both personally and officially, developers should adhere to stricter code standards, and in the modern PHP ecosystem, a unified style makes PHP code easier for other developers to understand.

Implement the PSR – 1

The PSR-1 should be implemented before using the PSR-2

The indentation

Use four Spaces for indentation.

There’s a lot of controversy about indentation. I used the IDE TAB key until I really looked at it. Then, when my colleagues and I write the same file, the indenting of the previous code will be different, resulting in a very messy code structure. So after the occurrence of this problem, unified the standard of document indentation, with four Spaces for the indent. This way, even if opened with an inconsistent editor, the effect is the same. Many ides can be set to TAB, which can be found in a Baidu search.

Files and lines of code

PHP files must use uniX-style line breaks (LF) with a blank line at the end and cannot be closed using PHP? > tag.

At first I didn’t understand why you don’t use close in pure PHP pages. Word-wrap: break-word! Important; “> < p style =” max-width: 100%

To avoid unexpected output errors, if a closing tag is applied and there is a blank line after the closing tag, this blank line is also considered output, resulting in an error (for example, when setting HTTP headers)

The keyword

Keyword, use lowercase;

I don’t know where I saw the PHP tutorial. The PHP code in the tutorial used uppercase true and false for keywords like true and false. I have been using it for a long time until I saw the pSR-2 specification

The namespace

Each namespace statement must be followed by an empty line. Similarly, when importing a namespace or creating an alias for a namespace using the use keyword, a blank line is followed by a series of USE declarations

Similar to:

<? PHP // Declare the namespace of this file namespace My\Friend; // Import namespace use Other\Friend; class GirlFrined { }Copy the code

class

The opening bracket of the class definition body should follow the class name on a separate line; The closing bracket of the class definition body must be written on a new line after the definition body.

Ex. :

<? php class Frined { public function getSex() { // do something } }Copy the code

methods

The opening bracket of the method definition body should follow the method name on a separate line; The closing bracket of the method body must be written on a new line after the method body;

Refer to the method example in the class example above.

visibility

Declare visibility for every property and method in a class. Visibility, which is specified by public, protected, or private, determines how the methods of the property are accessed inside and outside the class. If a class property is declared static, the qualifier must precede the visibility keyword. If a class property is declared static, the qualifier must precede the visibility keyword

Example:

// 1, 2 public $sex; private $_sex; protected $sex; If ($sex = $sex; final public $sex; // 4, public static $sex; public static $age;Copy the code

Control structure

All control structure keywords should be followed by a space. Control structure keywords include: if, elseif, else, switch, case, while, do while, for, foreach, try, catch. If a control structure keyword is followed by a pair of parentheses, there must be no space after the opening parentheses and no space before the closing parentheses. Unlike the definition bodies of classes and methods, the opening parentheses after the control structure keyword should be on the same line as the control structure keyword. Closing parentheses after control structure keywords must be written on a separate line.

Ex. :

/** * Examples of errors: * There are four errors: If (1 == true){// do something}else{// if(1 == true){// do something}else{// **/ if (1 == true) {// do something} else {// do something}Copy the code

Psr-3: Logger interface

Log recorder

The third recommendation published by PHP-FIG differs from the first two in that it is a bit special and is an interface. Specifies the methods that the PHP logger component can implement.

Loggers are objects used to write messages of varying importance to the specified output. The recorded messages are used to diagnose, examine, and troubleshoot operational, stability, and performance problems in the application. For example: the development of debugging information written to text files, the site traffic statistics recorded to the database and so on.

I believe that logging is implemented in almost all frameworks, so what should I do if I want to use the PSR-3 specification logger? First of all, two points should be met:

  1. The logging function is delegated to a third-party library
  2. End users can choose the logger component they prefer

Write the PSR-3 logger

A PHP logger component that complies with the PSR-3 recommendation must include a PHP class that implements the PSR \Log\LoggerInterface interface. The PSR-3 interface uses the RFC 5424 system logging protocol, which stipulates 9 methods to be implemented:

I took the following code from phP-FIG’s official website, if you want more information, please click me

<? php namespace Psr\Log; interface LoggerInterface { public function emergency($message, array $context = array()); public function alert($message, array $context = array()); public function critical($message, array $context = array()); public function error($message, array $context = array()); public function warning($message, array $context = array()); public function notice($message, array $context = array()); public function info($message, array $context = array()); public function debug($message, array $context = array()); public function log($level, $message, array $context = array()); }Copy the code

Each method in this class corresponds to a logging level of the RFC 5424 protocol and takes two parameters. The first argument must be a string, or an object that has a __toString() method. The second argument is an array, optional;

If you were to write loggers that conform to the PSR-3 specification, you would create a PHP class that implements the PSR \Log\LoggerInterface interface and provide a concrete implementation of each method in that interface

Use the PSR-3 logger

Since the PSR-3 specification came out, there have been so many components that I won’t show you how to implement this interface class. Monolog /monolog is recommended for mature logger components. This component is fully on-line with the PSR-3 interface and can be extended with custom message formatters and handlers. If monolog cannot meet the requirements of daily use, we can expand our own methods on the basis of monolog, which is also very simple.

Using monolog examples:

<? php use Monolog\Logger; use Monolog\Handler\StreamHandler; $logger = new logger ('my_logger'); $logger->pushHandler(new StreamHandler('logs/development.log', Logger::DEBUG)); $logger->pushHandler(new StreamHandler('logs/production.log', Logger::WARNING)); $logger->debug('This is debug message'); $logger->debug('This is warning message');Copy the code

Psr-4: Automatic loader

The fourth recommendation published by PHP-FIG describes a standard autoloader strategy; An autoloader simply means that a PHP class, interface, or trait is found and loaded into the loader as needed while the program is running.

Auto loader policy

The PSR-4 recommendation does not require changes in how the code is implemented, just how it is organized using file system directory structures and PHP namespaces. Psr-4 ** relies on PHP namespaces and file system directory structures to find and load PHP classes, traits, and interfaces

Why are autoloaders important

To take a very common scenario, we usually adopt the methods such as require and include to introduce files. This way is simple and reliable, but if we introduce one or two files, it is ok, but when we need to introduce dozens of files in a project running, we should not write dozens of require or include. This is not convenient, and not beautiful, so PHP-FIG on this basis to consider, standardize a unified autoloader strategy;

How do I use the autoloader

It is recommended to use the PSR-4 autoloader that is automatically generated by dependency manager Composer. Modern PHP frameworks such as Laravel, Yii, TP5, and others use an auto-loader strategy that relies on Composer to download components and import appropriate classes.

Psr-me: Write your own PHP specification

  1. Follow the usage specification of PSR-1 and PSR-2
  2. Proper, concise naming of variables, methods, and classes. So that people can look at it and see what it does
  3. Write as cohesive, low-coupling code as possible
  4. Keep the code structure clean and beautiful

conclusion

The PHP specification that comes out of PHP-FIG does not necessarily mean that all PHP developers must follow it. The goal of this specification is to make it easier and easier for PHP developers around the world to view their code. The components/wheels can be easily known and used by all developers, and at the same time reduce our work input rate, get greater work efficiency, make output more than input, efficiency is higher and faster.

I hope this will help you,Many PHPer will always encounter some problems and bottlenecks when they are advanced. They have no sense of direction because they write too much business code, so they don’t know where to start to improve. I have sorted out some information about this, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripting, Docker, micro services, Nginx, etcI need to poke herePHP advanced architect >>> Practical video, big factory interview documents for free