yii2-Core Framework Code specification

Source: Internet
Author: User

1. Overview

Simply put, we use the PSR-2 compatibility specification, so everything applied to PSR-2 is equally applicable to our code.

    • The file must use the <?php or <?= tag.
    • The file should have a new line at the end.
    • PHP code files must only use UTF-8 with no BOM.
    • The code indentation must use 4 spaces instead of the TAB key.
    • The class name must be declared with a large hump type (capitalized).
    • A constant in a class must be declared with an all-uppercase underline.
    • The method name must be declared with a small hump (lowercase first letter).
    • Property names must be declared with a small hump (lowercase first letter).
    • If it is a private property name, you must start with an underscore.
    • Use ElseIf instead of else if.
2. File 2.1.PHP Tag
    • PHP code must use <?php or <?= tags, must not use other label names, such as <
    • If there is only PHP in the file, it should not end with?>.
    • Do not add trailing spaces at the end of the file.
    • Any file that includes PHP code should be suffixed with. php.
2.2. Character encoding

PHP code files must only use UTF-8 with no BOM.

3. Class Name

The class name must be declared with a large hump type (capitalized). For example, Controller,model.

4. Class

The "class" Here involves all classes and interfaces.

    • The class should be named using the Big Hump (capitalized) method.
    • Parentheses should be written below the class name.
    • Each class must have a document section that conforms to Phpdoc.
    • All code in the class must have only one independent indent tab.
    • There should only be one class in a PHP file.
    • There should be namespaces for all classes.
    • The class name matches the file name. The class namespace should match the dictionary structure.
        /**         * Documentation         *        /class MyClass extends \yii\object implements MyInterface        {            //code        }    
4.1. Constants

A constant in a class must be declared with an all-uppercase underline. For example:

            <?php            class Foo            {                Const VERSION = ' 1.0 ';                Const date_approved = ' 2012-06-01 ';            }        
4.2. Properties
    • When declaring a public class member, be particularly explicit about the keyword common.
    • Public and protected variables should be declared before any method declaration. Private variables can be declared at the top of the class, but can also be added before the associated class method block is used.
    • The Order of attribute declarations in a class should be from public, protected to private.
    • For readability, there are no blank lines between attribute declarations and two blank rows between property and method declarations.
    • Private variables should be named $_varname like this.
    • public class members and independent variables should be named $camelcase in such a lowercase letter.
    • Use a description to name it. Variables are best not to be named with $i and $j.

For example:

            <?php            class Foo            {public                $publicProp;                protected $protectedProp;                Private $_privateprop;            }        
4.3. Methods
    • Functions and methods should be named Small hump with the first letter lowercase.
    • The name should reflect the functional description implemented by the function.
    • private,protected and public decorations should often be visible in class methods. var is not allowed.
    • The opening parenthesis of the method should be below the method.
            /**             * Documentation * * *            class Foo            {                /**                 * documentation *                * Public function Bar ()                {                    //code                    return $value;                }            }        
4.4. Document Block

Parameters, variables, properties, and return values must declare a type, such as Boolean,integer,string,array or null. You can also use the class name, like model or ActiveRecord. For example, you can use classname[for an array type].

4.5. Construction method
    • _construct should use the construction method of PHP 4.
5. PHP5.1. Data type
    • All data types and variables should be lowercase. Includes True,false,null and array.

It is not recommended to change the existing data types. Unless you have to write such a code.

            Public function Save (Transaction $transaction, $argument 2 = +)            {                $transaction = new Connection;//Bad                $arg Ument2 = 200; Good            }        
5.2. String
      • Use single quotation marks when you do not include variables or single quotation marks in a string.
                $str = ' like this. ';            
    • If there are single quotes in the string, you can use double quotes to avoid extra escaping.
Variable substitution
            $str 1 = "Hello $username!";            $str 2 = "Hello {$username}!";        

The following methods are not allowed:

            $str 3 = "Hello ${username}!";        
Connection

When connecting strings, use dots around spaces.

            $name = ' Yii '. ' FrameWork ';        

Long-content strings can be used in the following ways:

            $sql = "SELECT *"                . "From ' Post '                ." WHERE ' id ' = 121 ";        
5.3. Arrays

For arrays, we use the short array syntax in PHP 5.4.

Numeric index
    • Do not use negative numbers as indexes.

Use the following method to declare an array:

            $arr = [3,14,15, ' Yii ', ' FrameWork '];        

If there are too many elements, you can separate the branches:

            $arr = [                3, +, 6,                $test,                ' Yii ', ' Framework ',            ];        
Association

Use the following format to associate an array:

            $config = [                ' name ' = '  Yii ',                ' options ' = [' usephp ' = ' + True],            ];        
5.4. Control statements
    • The condition of the control statement must have a separate space before and after the insertion of the sentence.
    • The parentheses within the operator should be separated by a space.
    • The opening parenthesis is in the same line as the control statement.
    • The closing parenthesis should be a new line.
    • Parentheses are also used for statements that have only one row.
            if ($event = = = null) {                return new event ();            }            if ($event instanceof coolevent) {                return $event->instance ();            }            return null;            The following is not allowed:            if (! $model && NULL = = = $event)                throw new Exception (' Test ');        

Try to avoid when the statement is in effect, else after return. Use defensive conditions.

            $result = $this->getresult ();            if (empty ($result)) {              return true;            } else {              //process result            }        

To be superior to:

            $result = $this->getresult ();            if (empty ($result)) {              return true;            }            Process result        
Switch statement

Switch uses the following format:

            Switch ($this->phptype) {case                ' string ':                    $a = (string) $value;                    break;                Case ' integer ': case                ' int ':                    $a = (int) $value;                    break;                Case ' Boolean ':                    $a = (bool) $value;                    break;                Default:                    $a = null;            }        
5.5. Function calls
        DoIt (2, 3);        DoIt ([' a ' = = ' B ']);        DoIt (' A ', [            ' a ' = ' = ' B ',            ' C ', ' = ' d ',        ]);    
5.6. Anonymous function (lambda) declaration

Use spaces before the Function/use parameter and statement:

        Good        $n =;        $sum = array_reduce (s, function ($r, $x) use ($n) {            $this->domagic ();            $r + = $x * $n;            return $r;        });        Bad        $n = +;        $mul = array_reduce (s, function ($r, $x) use ($n) {            $this->domagic ();            $r *= $x * $n;            return $r;        });    
Document
      • Refer to the Phpdoc document syntax.
      • Code that does not have a document is not allowed.
      • All class files must include a file-level document block in each file. Also, the class-level document blocks are directly above each class.
      • You do not need to use @return if the method does not return any content.
      • All virtual properties in the class that inherit from Yii\base\object are marked as @property in the class document block. These annotations are automatically run from the getter and setter./bulid Php-doc when @return and @param are generated. You can add a @property tag to the getter or setter, forcing a description of the property to be described differently than the first @return. Here's an example:
                  <?php                  /**                   * Returns The errors for all attribute or a single attribute.                   * @param string $attribute attribute name. Use the null to retrieve errors for all attributes.                   * @property array An array of errors to all attributes. Empty array is returned if no error.                   * The result is a two-dimensional array. see [[GetErrors ()]] For detailed description.                   * @return Array errors for all attributes or the specified attribute. Empty array is returned if no error.                   * Note that if returning errors for all attributes, the result was a two-dimensional array, like the following:                   *. .                   *                  /Public Function geterrors ($attribute = null)            
File
            <?php            /**             * @link http://www.yiiframework.com/             * @copyright Copyright (c) Yii software LLC             * @ License http://www.yiiframework.com/license/             */        
Class
            /**             * Component is the base class that provides the *property*, *event* and *behavior* features.             * *             @include @yii/docs/base-component.md             *             * @author Qiang Xue <[email protected]>             * @since 2.0             */            class Component extends \yii\base\object        
Functions/Methods
            /**             * Returns the list of attached event handlers for an event.             * Manipulate the returned [[Vector]] object by adding or removing handlers.             * For example,             *             ~ ~ ~             $component->geteventhandlers ($eventName)->insertat (0, $eventHandler);             * ~ ~ ~ *             @param string $name the event name             * @return Vector List of attached event handlers for the Event
   * @throws Exception If the event is not defined             *            /Public Function geteventhandlers ($name)            {                if ( !isset ($this->_e[$name])) {                    $this->_e[$name] = new Vector;                $this->ensurebehaviors ();                return $this->_e[$name];            }        
Label (Markdown)

As you can see in the example above, we use tags to format phpdoc content.

The following is another syntax used for connections between classes, methods, and properties in a document:

    • ' [[[Cansetproperty]] ' is used to create a connection in the Cansetproperty method or property in the same class.
    • ' [[[Component::cansetproperty]] ' is used to create a connection in the same namespace within the Component class Cansetproperty method.
    • ' [[[Yii\base\component::cansetproperty]] ' is used to create a Cansetproperty method in the Component class that is connected within the Yii\base namespace.

To connect the other label classes or method names mentioned above, you can use the following syntax:

            ... as displayed in the [[Header|header Cell]].        

When | followed by a join tag, before | Is the method, property, or class related.

Of course, you can also connect to the bootstrap using the following code:

            [link to guide] (GUIDE:FILE-NAME.MD)            [link to guide] (guide:file-name.md#subsection)        
Comments
    • Single-line comments can be started using//instead of #.
    • A single line comment is valid only for the current row.
other rules = = = [] VS empty ()

Use empty () whenever possible.

Multiple return points

When conditional nesting is confusing, return as early as possible. If the method is shorter, there is no relationship.

Self vs Static

Persist using static unless the following scenario appears:

    • Get constants must pass Self:self::my_constant
    • Get private property must pass Self:self::$_events
    • You can use self to recursively invoke the current implementation instead of the extension class.
Value for "Don ' t Something"

Properties can be configured to receive False,null, ' or [] values by formulating components to not do something.

Dictionary/namespace name
    • Use lowercase letters
    • When representing an object, use the form of a complex number (for example, validators)
    • yii2-Core Framework code specification when representing related features or features, using singular forms (e.g., web)

yii2-Core Framework 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.