PHP psr-[0-4] Code specification

Source: Internet
Author: User
Tags autoload coding standards deprecated try catch zend

Php-fig

Before saying what is psr-[0-4] specification, I think we need to say its inventor and spec: Php-fig, its website is: www.php-fig.org. This is the union organization invented and created the psr-[0-4] norms, worship it, dick Silk!

FIG is the abbreviation of the Framework Interoperability Group (framework Interoperability Group), which was founded in 2009 by several developers of open source frameworks, and since then, many other members have been selected, although not "official" organizations, but also represent a small chunk of the community. The purpose of the organization is: to the minimum limit, to unify the coding specifications of the various projects, to avoid the style of self-development hindered the development of the programmer's trouble, so we invented and summed up the PSR,PSR is proposing a standards Recommendation (standard recommendations), so far, a total of 5 sets of PSR specifications, respectively:

PSR-0 (autoloading standard) automatic loading standards
PSR-1 (Basic Coding Standard) basic coding standards
PSR-2 (Coding style guide) Coding Style Wizard
PSR-3 (Logger Interface) Log interface
PSR-4 (improved autoloading) automatic loading of the enhanced version, you can replace the PSR-0.

The next contents, we will focus on these 5 sets, in-depth understanding. Carefully study under the thousands of Phper hot hold of the 5 sets of specifications in the end what is the outstanding.

PSR-0 Specification

PRS-0 specification is their 1th set of specifications, mainly developed a number of automatic loading standards (autoloading standard), if you are better in English, you can directly crossing this: PSR-0, very short. But if your English rotten into a dog, then continue to look at my blindness to explain it!

When we opened PSR-0 's homepage, we found a warning:

Deprecated-as of 2014-10-21 PSR-0 has been marked as Deprecated. PSR-4 is now recommended as an alternative.

English dog bad, come, listen to me translate:

Deprecated-PSR-0 has been marked as obsolete on October 21, 2014. PSR-4 is now recommended as an alternative.

So that means PSR-0 already! By A When The , Don't Cry, PHP code dog. Although it is outdated, but we can also look at it, this does not affect our study, OK. Don't talk nonsense, let's get started:

PSR-0 Mandatory Requirements several:

  1. A fully qualified Namespace and class must conform to this structure: "\< Vendor name> (< namespace>) *< Class name>"
  2. Each namespace must have a top-level namespace ("Vendor name" provider name)
  3. Each namespace can have multiple sub-namespace
  4. When loaded from the file system, each namespace delimiter (/) is converted to Directory_separator (operating system path delimiter)
  5. In the class name, each underscore (_) symbol is converted to Directory_separator (the operating system path delimiter). In namespace, the underscore (_) symbol has no (special) meaning.
  6. When loaded from the file system, the qualified namespace and class must end in. php.
  7. Verdor name,namespaces,class names can be combined in uppercase and lowercase letters (case sensitive)

is not a bit to understand AH. What namespace ah, what autoloading ah. So, if you are not particularly aware of the namespace, you can Google under namespace and automatically load the relevant PHP knowledge. Or take a look at the next article, I specifically say them: namespace and autoloading

OK, let's take a few examples to analyze the following:

1th article

For example, my file/doctrine/common/isolatedclassloader.php a class file like this, then your namespace name must declare this:

Declaration: Namespace  \doctrine\common Call: \doctrine\common\isolatedclassloader

Where Doctrine represents a module directory Vendor name, Common is Namesapce, Isolatedclassloader is class name. Such a look will know the directory hierarchy of this file, at a glance.

Another example:/path/to/project/lib/vendor/symfony/core/request.php file:

Declaration: Namespace \symfony\core Call: \symfony\core\request
2nd, article 3
namespace \zend\acl =/path/to/project/lib/vendor/zend/acl.phpnamespace \zend\mail\message =/path/to/ project/lib/vendor/zend/mail/message.php

There must be a top-level Zend namespace, Zend The following can have a message child namespace.

4th article

Look at this example, we need a new class like this.

New \symfony\core\request

So when I load this class file again, I'm going to convert the delimiter \ into a directory, that is, go to Vendor----symfony->core->request.php layer of directory to find this file. In fact, the corresponding relationship with the first is the opposite.

5th article

5th is said that the namespace name in the _ symbol is not any use, is used to represent the directory delimiter, but notice in PRS-4 has canceled this _, then we still look at, this outdated rule is how:

\namespace\package\class_name =/path/to/project/lib/vendor/namespace/package/class/name.php\namespace\ Package_name\class_name =/path/to/project/lib/vendor/namespace/package_name/class/name.php

The _ in the above 2 namespace is actually a directory separator. That's not what class name is. Now, after PSR-4 out, I do feel that such a rule is a little bad. It's weird.

6th article

6th don't say much. Since you use PHP, the filename is, of course, the end of the. php suffix. The reason for this rule, I guess roughly, is someone using the. php3 suffix. All right. This is a myth. Because it is allowed in the Apache configuration file:

<ifmodule dir_module>    directoryindex index.php index.php3 index.html index.htm</ifmodule>

So, be honest with. php as the suffix name.

7th article

File capitalization problem, this is actually very important. Because the Linux system is distinguished by file name and directory name capitalization, it is not differentiated under Windows. So there are often problems, such as:

Namespace  \doctrine\common\isolatedclassloader

Under Linux, go to the directories and files strictly according to the size. But if you develop under Windows, all lowercase will not error, you publish to Linux on the tragedy, prompted to find the file. So, capitalization is too important.

PSR-1 Specification

Or that sentence, if you English is better, you can directly crossing this: PSR-1, also not long, basic can read. But if your English rotten into a dog, then please continue to look down on my blind!

  1. PHP source files must use only the <?php and <?= tags.
  2. The encoding format of the PHP code in the source file must be UTF-8 without a byte order mark (BOM).
  3. A source file is recommended only for declarations (classes, functions, constants (constant), etc.) or only for actions that cause side effects (for example, output information, modify. ini configuration, etc.), but it is not recommended to do both things at the same time.
  4. Namespaces (namespace) and classes (class) must comply with the PSR-0 standard.
  5. The class name must be written using Camel (StudlyCaps) (note: A variant of the Hump (Camecase), which will be expressed directly in StudlyCaps).
  6. Constants in class must consist only of uppercase letters and underscores (_).
  7. Method name must be used in camel (camecase) notation.

Good, is the above basic 7 big point, some very simple, does not have too much to explain, 3rd need to carefully say.

1th article

This is basically what everybody knows, PHP code must use only long label (<?php?>) or short output type label (<?=?>), do not use other tags.

This is because we are learning PHP, the general textbook tells us that PHP has 4 kinds of markup style: PHP 4 kinds of marker style so, a lot of people are crazy. The blind Dick wrote. Especially ASP style part-time is torture good!!!

2nd Article

This does not say, save the time format must be no BOM UTF-8 format , otherwise there will be a lot of unexplained strange problems. Don't be a jerk. Save the file with the text editor under Windows

3rd article

That's what the layman says. Just don't mix some of the output and modified operations (side effects) with the class files, focus on this file specifically to declare class, that file specifically to modify the configuration file, do not mix together write:

Therefore, the following file is problematic, it is best not to:

Side effects: Modified INI configuration ini_set (' error_reporting ', e_all);//Side effects: Loaded file include "file.php";//Side effects: output echo "

You see how messy it looks. It's best to write it all apart:

Namespace Lib;class name{public function __construct () {echo __namespace__. "<br>";} public static function test () {echo __namespace__. ' Static function Test <br> ';}}

Modify INI:

Ini_set (' error_reporting ', e_all);

Require file:

Require DIR. '/loading.php '; Spl_autoload_register ("\\autoloading\\loading::autoload");

Do you think it's more neat? Of course, this is hard to restrain. themselves carefully divided.

4th article

The 4th one is bound namespace, which has been said before, not much. It's worth saying that the name is the hump way.

5th article

Class name must be written in camel, hump and small hump and big hump (small hump is the first letter is lowercase) so write to look comfortable also more norms, do not require, anyway is the hump on it can be. I like to use a small hump:

Class getuserinfo{}
6th article

The constant name (const) declaration in the specified class must be capitalized, and if there are multiple words, separate them with _:

Class getuserinfo{//All caps const NAME = ' phper ';//with _ separated const House_info = ' already shenzhen buy house ';p ublic function GetUserName () {//}}?
7th article

Method name must be written in camel style, size hump can, do not require, I like to use small hump:

Class Getuserinfo{public function GetUserName () {//}}
PRSR-2 Specification

PSR-2 specifications of the official website link here: PSR-2 This specification is mainly binding code style, but that is all inside the most important, but also need to be well regulated and common adherence.

We take a look, can only I write some of the more important, or usually use the most.

1. Source Files
    1. A blank line must be at the end of the file.
    2. You must use UNIX LF (line feed) as the line terminator.
    3. The close tag of the pure PHP code source file?> must be omitted.

The 3rd is actually very important, I was still old write closed, now do not write. This avoids having to accidentally add a space or line break after the PHP end tag, which causes PHP to start outputting these blanks, and there is no intention to output the script at this time.

2. Indent

You must use 4 spaces to indent, and you cannot use the TAB key. Of course you can manually set the tab to 4 spaces in the editor. This is because: everyone's machine Tab key is different, some are 4 spaces, some are 8 spaces, on your machine looking very cool code, on the other machine on the various disgusting. So, unified into 4 spaces, no matter where open is beautiful.

3, line

A line recommendation is to write up to 80 characters, more than this character should be wrapped, the general editor can be set.

4. Keywords and true/false/null

The PHP keyword must be lowercase, Boolean: true,false,null must also be lowercase

Below is the PHP keyword, which must be lowercase.

' __halt_compiler ', ' abstract ', ' and ', ' array ', ' as ', ' break ', ' callable ', ' case ', ' Catch ', ' class ', ' Clone ', ' const ', ' con Tinue ', ' Declare ', ' Default ', ' die ', ' do ', ' echo ', ' Else ', ' elseif ', ' empty ', ' enddeclare ', ' endfor ', ' Endforeach ', ' endif ' ', ' endswitch ', ' endwhile ', ' eval ', ' exit ', ' extends ', ' final ', ' for ', ' foreach ', ' function ', ' global ', ' goto ', ' If ', ' imp Lements ', ' include ', ' include_once ', ' instanceof ', ' insteadof ', ' interface ', ' isset ', ' list ', ' namespace ', ' new ', ' or ', ' print ', ' private ', ' protected ', ' public ', ' require ', ' require_once ', ' return ', ' static ', ' switch ', ' throw ', ' trait ', ' try ', ' unset ', ' use ', ' var ', ' While ', ' XOR '

5. Namespaces (Namespace) and import (use) Declarations

The following is a simple text description:

    1. The Declaration of the namespace (namespace) must be followed by a blank line.
    2. All the import (use) declarations must be placed under the namespace (namespace) declaration.
    3. In a statement, you must have only one import (use) keyword.
    4. You must have a blank line after the import (use) Declaration code block.

Use the code to illustrate the following:

<?phpnamespace lib\databases; The following must be a space line class mysql{}

namespace a blank line before you can declare class by using use and an empty line.

<?phpnamespace lib\databases; The following must be a blank line use Foointerface; Use must declare the use Barclass as Bar;use Othervendor\otherpackage\bazclass after namespace; The following must be a space line class mysql{}
6. Classes (class), Attributes and Methods (method)

(1), inheritance (extends) and implementation (implement) Must and class name written in a line, cut flower brackets to write a newline.

<?phpnamespace Lib\databaes;class Mysql extends ParentClass implements \PDO, \db//write a line {//newline write {}

(2), the property must declare its visibility, whether public or protected or private, can not be omitted, and can not use Var, var is the old version of PHP in what way, and so on public.

<?phpnamespace Lib\databaes;class Mysql extends ParentClass implements \PDO, \db//write a line {public $foo = Null;private $nam E = ' Yangyi ';p rotected $age = ' 17 ';}

(3), method, must declare its visibility, whether public or protected or private, can not be omitted. Also, curly braces {must be wrapped and written. If there are multiple parameters, the first argument is followed by a space, and the function name and (must have a space between: Function_name ($par, $par 2, $pa 3), if the parameter has a default value, also use left and right spaces separate.

<?phpnamespace Lib\databaes;class Mysql extends ParentClass implements \PDO, \db//write a line {public getInfo ($name, $age, $g Ender = 1)//function name GetInfo and (there is a space between the arguments, there should be spaces between the parameters.) Default parameters also have space around {//must wrap write {}}

(4), when using abstract and finalization (final) to make class declarations, they must be placed before the visibility declaration (public or protected or private). When static is used to make a class declaration, it must be placed behind the visibility declaration.

Directly on the code:

<?phpnamespace vendor\package;abstract class classname{protected static $foo;//static on the back abstract protected function Zim (); Abstract put front final public static function bar ()//final put front, static put last. {//Method body part}}
7. Control Structure

The control interface is the if else while switch. This type of code is often prone to problems, but also to standardize.

(1), if,elseif,else writing, directly on the code bar:

<?phpif ($expr 1) {///left/Right space//If Body} elseif ($expr 2) {//Elesif attached write//ElseIf body} else {//else body;}

(2), switch,case note the left and right spaces and line-wrapping, or directly on the canonical code:

<?phpswitch ($expr) {////left/Right Space case 0:echo ' first case, with a "break"; Case 1:echo ' Second case, which falls through ';//No breakcase 2:case 3:case 4:echo ' third case, return instead of break '; Return;default:echo ' default case ';

(3), while,do while the wording is similar, to the left and right space, on the code:

<?phpwhile ($expr) {///structure Body}do {//structure body;//left and right spaces} while ($expr);

(4), for the wording of

<?phpfor ($i = 0; $i < $i + +) {//Note the space between several parameters//for body}

(5), the wording of foreach

<?phpforeach ($iterable as $key = + $value) {//or whitespace issue//foreach Body}

(6), try Catch

<?phptry {//try body} catch (Firstexceptiontype $e) {//Also note spaces. Catch body} catch (Otherexceptiontype $e) {//Catch body}

The basic use of this is these, and other what the closure of what the use of not much is not too much of the exhaustion of the statement.

PSR-3 Specification

PSR-3 specification is mainly to standardize the log interface (Logger Interface), frankly speaking, in fact, the usual contact is not particularly much, so do not say, you can go to crossing the PSR-3 of the net

PSR-4 Specification

The PSR-4 specification is a new specification for how long it has just haunted, it is also a specification automatic loading (autoload), is the modification of PSR-0, belongs to the supplementary specification,

I would simply say that the following are the main points:

    1. The PSR-0 is the name of the directory separator, _ underscores in the fully qualified class names do not have a special meaning.
    2. The class file name should end in. php.
    3. The class name must be exactly the same as the corresponding file name, and the case should be identical.

Reference:

http://segmentfault.com/a/1190000000380008

http://www.4wei.cn/archives/1002186

Http://wenku.baidu.com/view/7a21e44b48d7c1c708a14577.html#10002-tsina-1-87843-e29b4784eda5d1f51fb0c2a97a15da08

Https://github.com/hfcorriez/fig-standards

PHP psr-[0-4] Code specification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.