PSR Specification 0-4 Finishing

Source: Internet
Author: User
Tags autoloader modifier switch case try catch
PSR Specification

PSR Specification

Introduction: PSR is a shorthand for PHP standard recommendations, PHP specifications developed by the PHP FIG organization, is the practice of PHP development standards. The purpose of these specifications is to: through the framework of the author or the representative of the framework of the discussion, with the minimum limit, the development of a collaborative standard, each framework to follow a unified coding norms, to avoid the development of the style of the self-development of PHP, to solve the long-standing problem of this program designer. As of the author's article on the PSR in a total of 11 sets of specifications, the following describes four of them and has been deprecated psr0 specifications.

PSR-0 (Autoloading Standard) 自动加载标准 (2014年10月21起被官方弃用 由psr4替代)PSR-1 (Basic Coding Standard) 基础编码标准 PSR-2 (Coding Style Guide) 编码风格向导 PSR-3 (Logger Interface) 日志接口 PSR-4 (Improved Autoloading) 自动加载的在用版本。#注:另有psr6(缓存接口规范)psr7(HTTP消息接口规范)psr11、psr13、psr15、psr16、psr17本文不做介绍

Attached official website address PSR

PSR0 (officially obsolete)

Auto Load Standard

    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 is converted to Directory_separator (the operating system path delimiter). In namespace, there is no (special) meaning to underline.
    6. When loading from the file system, the qualified namespace and class must be the Verdor Name,namespaces,class name with the end of. PHP (case sensitive)

Note: Because it is obsolete, there is no more introduction

Psr4

Here first introduce PSR4, good compared with the above psr0, because he is the upgrade version of the PSR-0 automatic loading specification
PSR4 is about the specification of automatic loading of corresponding classes by file paths, and this specification is interoperable. Can be used as a supplement to any automatic (including PSR-0) loading specification, in addition, PSR4 also includes the file storage path specification for automatically loaded classes.

The "class" Here refers to all class classes, interfaces, traits reusable blocks of code, and other similar structures.
A complete class name needs to have the following structure
< namespaces > (< sub-namespaces >) *< class name >

    1. The full class name must have a top-level namespace called "Vendor namespace"
    2. The full class name can have one or more child namespaces
    3. The complete class name must have a final class name
    4. An underscore in any part of a complete class name has no special meaning.
    5. The full class name can be made up of any uppercase and lowercase letters
    6. All class names must be case-sensitive

When loading the corresponding file according to the full class name

    1. In the complete class name, the first namespace delimiter is removed, one or more contiguous namespaces and child namespaces, which must correspond to at least one underlying directory, as "namespace prefixes".
    2. The child namespace immediately following the namespace prefix must match the corresponding "base directory" subdirectory, where the namespace delimiter is used as the directory separator
    3. The class name at the end must have the same name as the corresponding. php suffix file.
    4. The implementation of the autoloader (autoloader) must not throw an exception, must not trigger any level of error information, and should not have a return value.

For example:

#完整的类名为\a\b\c\Log#命名空间前缀前缀为:a\b#前缀对应的基础目录为:./vendor#文件实际目录为:./vendor/c/Log.php#注:即把去掉最前面的命名空间分隔符后的a\b\c\Log中的命名空间前缀替换成基础目录,然后把命名空间分隔符替换成目录分隔符,并把文件名补上后缀 .php 。

The biggest difference between PSR-4 and PSR-0 is that the underscore (underscore) is defined differently. In PSR-4, the use of underscores in class names does not have any special meaning. PSR-0 Specifies that the underscore _ in the class name will be converted to a directory delimiter.

PSR1 Basic Code specification
    1. PHP source files must use only the <?php and <?= tags. (PHP tags are available in several ways)
    2. The encoding format of the PHP code in the source file must be UTF-8 without a byte order mark (BOM). (Note: PHP does not consider BOM at design time, that is, he will not ignore the UTF-8 encoded file at the beginning of the BOM three bytes caused by a strange error.) )
    3. A source file is recommended only for declarations (classes, functions, constants (constant), etc.) or only for actions that cause a subordinate effect (for example: output information, include files, modify. ini configuration, etc.), but not both.
      Note: The term "subordination effect" (side effects) means that the logical operation is performed only by including files, not directly declaring classes, functions and constants, etc. The "dependent effects" include, but are not limited to, generating output, direct require or include, connecting to external services, modifying INI configuration, throwing errors or exceptions, modifying global or static variables, reading or writing files, and so on. This is a lot of people do not obey, but basically all the framework will not change. INI configuration and declaration classes or functions together, such as the framework index.php Portal file only define macro constants and modify. INI, etc.

    4. Namespaces (namespace) and classes (class) must comply with PSR0 or PSR4 standards.
    5. The class name must be written using Camel (StudlyCaps) (Note: StudlyCaps is the First Capital camel).
    6. Constants in class must consist only of uppercase letters and underscores.
    7. Method name must be used in camel (camecase) notation.

PSR2 Code Style
    The
    1. code must follow the encoding specification in PSR-1
    2. code must use four space characters instead of the TAB key to indent.
    3. the number of characters per line should be kept soft within 80, theoretically not more than 120, but must not be hard to restrict
    4. each namespace namespace declaration statement and use statement block, you must insert a blank line
    5. The opening curly brackets of a class must be self-formed after the class declaration, and the end of the flower name must also be a line after the body of the class
    6. the opening brace of the function must be one line after the function declaration, and the end of the flower name must also be a line after the body of the function
    7. The properties and methods of the class must add access modifiers (private protected and public), abstract and final must be declared before the access modifier, and static must be declared after the access modifier.
    8. You must have a space character after the key for the control structure, but you cannot call a method or function. The opening curly brace of the
    9. control structure must be written on the same line as the declaration, and the closing curly brace must be written in a row after the body.
    10. There must be no whitespace in the beginning of the opening parenthesis of the control structure and before the closing parenthesis.
      Sample Code
<?php    namespace Vendor\Package;        use FooInterface;    use BarClass as Bar;    use OtherVendor\OtherPackage\BazClass;        class Foo extends Bar implements FooInterface    {        public function sampleMethod($a, $b = null)        {            if ($a === $b) {                bar();            } elseif ($a > $b) {                $foo->bar($arg1);            } else {                BazClass::bar($arg2, $arg3);            }        }            final public static function bar()        {            // method body        }    }

There are usually the following points to note

for PHP Files:

    • All PHP files must have a Unix LF (newline) as the Terminator
    • All PHP files must end with a separate blank line
    • The close tag of the pure PHP code source file?> must be omitted.

Keywords and true/false/null

    • PHP keyword, must lowercase
    • PHP output True, false,null must also be lowercase

Name space

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

For example:

<?phpnamespace Vendor\Package;use FooClass;use BarClass as Bar;use OtherVendor\OtherPackage\BazClass;// ... additional PHP code ...

Control structure

If, else, ElseIf, while, do and switch case, for, foreach,try catch, and so on. This type of code is often prone to problems, but also to standardize. A space should be added between the keyword and the following judgment condition, and a space between the judging condition and the left brace.

PSR3 Log Interface Specification

The main purpose of this specification is to let the class library receive a Psr\log\loggerinterface object in a simple and generic way to log information. Frameworks and CMS content management systems can extend interfaces for their own use, if needed
Purpose, but must follow this specification, in order to use the third party's class library file, ensure that the log interface can still be properly docked.

The Loggerinterface interface defines eight methods for documenting the eight levels defined in RFC 5424: Debug, info, notice, warning, error, critical, alert,emergency.

The Nineth method-log, whose first parameter is the rank of the log, can call this method with a predefined rank constant as a parameter and must have the same effect as calling the eight methods directly. If an incoming rank constant parameter is not predefined, you must throw an exception of type psr\log\invalidargumentexception, and in an indeterminate case, the consumer should not use an unsupported level constant to invoke this method. If you use Monolog, you should have a deeper understanding of it.

For example, the log level can be defined as follows:

    <?php        namespace Psr\Log;        /**     * Describes log levels     */    class LogLevel    {        const EMERGENCY = 'emergency';        const ALERT     = 'alert';        const CRITICAL  = 'critical';        const ERROR     = 'error';        const WARNING   = 'warning';        const NOTICE    = 'notice';        const INFO      = 'info';        const DEBUG     = 'debug';    }

Log here presumably everyone contact is not much, if want to know can look at Monolog source code.
This is the end of this article, I hope you get to the desired knowledge.

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.