PHP代码风格和最佳实践

PHP代码风格和最佳实践

  1. Coding Style

    1. PSR-1 基础编码规范

        1. Class name must CamelCaps 
            1. brace another line 
        2. Method
            1. StudlyCaps 
            2. camelCaps
            3. under_score
    2. PSR-2 编码风格规范

        1. Control structure keywords MUST have one space after them; method and function calls MUST NOT.
        2. Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.
    3. Function

        1. Allman style 
    4. Variable

        1. camelCaps
  2. Best Practice

    1. Storing passowrd use password_hash/password_verify function

    2. connect mysql use PDO class

    3. Auto-loading class use spl_autoload_register() function

    4. Single vs. double quotes from a performance perspective
      It doesn’t really matter. awlays use same style

    5. Use define() unless readability, class constants, or micro-optimization are concerns.

    6. PHP and Memcached If you need a distributed cache, use the Memcached client library. Otherwise, use APCu.

    7. PHP and regex Use the PCRE (preg_*) family of functions.

    8. Sending email Use PHPMailer.

    9. Validating email addresses Use the filter_var() function.

    10. Sanitizing HTML input and output Use the htmlentities() function for simple sanitization and the HTML Purifier library for complex sanitization.

    11. Working with dates and times Use the DateTime class.

    12. Checking if a value is null or false Use the === operator to check for null and boolean false values.

  3. Eaxmple

<?php
namespace Vendor\Package;

use FooInterface;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class Foo extends Bar implements FooInterface
{
    public function sampleFunction($a, $b = null)
    {
        if ($a === $b) {
            bar();
        } elseif ($a > $b) {
            $foo->bar($arg1);
        } else {
            BazClass::bar($arg2, $arg3);
        }
    }

    final public static function bar()
    {
        // 方法的内容
    }
}
<?php
switch ($expr) {
    case 0:
        echo 'First case, with a break';
        break;
    case 1:
        echo 'Second case, which falls through';
        // no break
    case 2:
    case 3:
    case 4:
        echo 'Third case, return instead of break';
        return;
    default:
        echo 'Default case';
        break;
}
<?php
for ($i = 0; $i < 10; $i++) {
    // for body
}
<?php
foreach ($iterable as $key => $value) {
    // foreach body
}

Reference:

  1. PHP Best Practices

标签: none

添加新评论