• PSR —— PHP Standard Recommendations


    本文只是对PSR中的overview的摘录,不足以覆盖推荐标准的全部内容。具体细节参考官网,或PSR编码规范(中文版)。其中,中文版对官网的规范进行了翻译,便于阅读。但是用例方面,虽然也是复制自官网用例,但是用例的格式已经发生错误,用例应该参考官网。

    1. PSR-1: Basic Coding Standard

      "This section of the standard comprises what should be considered the standard coding elements that are required to ensure a high level of technical interoperability between shared PHP code."

      • Files MUST use only <?php and <?= tags.

      • Files MUST use only UTF-8 without BOM for PHP code.

      • Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.

      • Namespaces and classes MUST follow an “autoloading” PSR: [PSR-0, PSR-4].

      • Class names MUST be declared in StudlyCaps.

      • Class constants MUST be declared in all upper case with underscore separators.

      • Method names MUST be declared in camelCase.

      上述标准中,第三条比较费解。更进一步的解释如下:
      A file SHOULD declare new symbols (classes, functions, constants, etc.) and cause no other side effects, or it SHOULD execute logic with side effects, but SHOULD NOT do both.

      The phrase “side effects” means execution of logic not directly related to declaring classes, functions, constants, etc., merely from including the file.

      “Side effects” include but are not limited to: generating output, explicit use of require or include, connecting to external services, modifying ini settings, emitting errors or exceptions, modifying global or static variables, reading from or writing to a file, and so on.

      "side effect"不能够被理解成“副作用”而应该是“附作用”,是指执行了和“declaring classes, functions, constants, etc” 不直接关联的逻辑执行操作。换言之,就是要把申明和执行分开,放在不同的文件中,那些申明通过include、require导入。
    2. PSR-2: Coding Style Guide
      是对PSR-1的扩展。本Guide的意图是“降低在阅读来自不同作者编写的代码时的歧义”。
      • Code MUST follow a “basic coding standard” PSR [PSR-0].

      • Code MUST use 4 spaces for indenting, not tabs.

      • There MUST NOT be a hard limit on line length; the soft limit MUST be 120 characters; lines SHOULD be 80 characters or less.

      • There MUST be one blank line after the namespace declaration, and there MUST be one blank line after the block of use declarations.

      • Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.

      • Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.

      • Visibility MUST be declared on all properties and methods; abstract and final MUST be declared before the visibility; static MUST be declared after the visibility.

      • Control structure keywords MUST have one space after them; method and function calls MUST NOT.

      • Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.

      • Opening parentheses for control structures MUST NOT have a space after them, and closing parentheses for control structures MUST NOT have a space before.

      例如:
       1 <?php
       2 namespace VendorPackage;
       3 
       4 use FooInterface;
       5 use BarClass as Bar;
       6 use OtherVendorOtherPackageBazClass;
       7 
       8 class Foo extends Bar implements FooInterface
       9 {
      10     public function sampleMethod($a, $b = null)
      11     {
      12         if ($a === $b) {
      13             bar();
      14         } elseif ($a > $b) {
      15             $foo->bar($arg1);
      16         } else {
      17             BazClass::bar($arg2, $arg3);
      18         }
      19     }
      20 
      21     final public static function bar()
      22     {
      23         // method body
      24     }
      25 }
      View Code
    3. PSR-3
    4. PSR-4: Autoloader
      PSR-4规范了如何指定文件路径从而自动加载类定义,同时规范了自动加载文件的位置。
      功能上,PSR-4和PSR-0有所重复。但是PSR-4是对PSR-0的升级,当时不是兼容性升级,并没有覆盖。另外PSR-0、PSR-4以及其他自动加载规范可以共同使用。
      PSR4标准与PSR0标准的区别:
      1. 在类名中使用下划线没有任何特殊含义。
      2. 命名空间与文件目录的映射方法有所调整
      规范如下:
      1. The term “class” refers to classes, interfaces, traits, and other similar structures.

      2. A fully qualified class name has the following form:

         <NamespaceName>(<SubNamespaceNames>)*<ClassName>
        
        1. The fully qualified class name MUST have a top-level namespace name, also known as a “vendor namespace”.

        2. The fully qualified class name MAY have one or more sub-namespace names.

        3. The fully qualified class name MUST have a terminating class name.

        4. Underscores have no special meaning in any portion of the fully qualified class name.    //与PSR-0的差别,PSR-0会将‘_’替换为directory separator

        5. Alphabetic characters in the fully qualified class name MAY be any combination of lower case and upper case.

        6. All class names MUST be referenced in a case-sensitive fashion.

      3. When loading a file that corresponds to a fully qualified class name …

        1. A contiguous series of one or more leading namespace and sub-namespace names, not including the leading namespace separator, in the fully qualified class name (a “namespace prefix”) corresponds to at least one “base directory”.  //namespace prefix与base directory对应。并且一个namespace prefix可以对应多个base directory,见下方代码中的例子。

        2. The contiguous sub-namespace names after the “namespace prefix” correspond to a subdirectory within a “base directory”, in which the namespace separators represent directory separators. The subdirectory name MUST match the case of the sub-namespace names.  //namespace prefix后的子域名对应于base directory下的子目录

        3. The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.  

      4. Autoloader implementations MUST NOT throw exceptions, MUST NOT raise errors of any level, and SHOULD NOT return a value.

      例子:
      Fully Qualified Class NameNamespace PrefixBase DirectoryResulting File Path
      AcmeLogWriterFile_Writer AcmeLogWriter ./acme-log-writer/lib/ ./acme-log-writer/lib/File_Writer.php
      AuraWebResponseStatus AuraWeb /path/to/aura-web/src/ /path/to/aura-web/src/Response/Status.php
      SymfonyCoreRequest SymfonyCore ./vendor/Symfony/Core/ ./vendor/Symfony/Core/Request.php
      endAcl Zend /usr/includes/Zend/ /usr/includes/Zend/Acl.php

      <?php
      namespace Example;
      
      /**
       * An example of a general-purpose implementation that includes the optional
       * functionality of allowing multiple base directories for a single namespace
       * prefix.
       *
       * Given a foo-bar package of classes in the file system at the following
       * paths ...
       *
       *     /path/to/packages/foo-bar/
       *         src/
       *             Baz.php             # FooBarBaz
       *             Qux/
       *                 Quux.php        # FooBarQuxQuux
       *         tests/
       *             BazTest.php         # FooBarBazTest
       *             Qux/
       *                 QuuxTest.php    # FooBarQuxQuuxTest
       *
       * ... add the path to the class files for the FooBar namespace prefix
       * as follows:
       *
       *      <?php
       *      // instantiate the loader
       *      $loader = new ExamplePsr4AutoloaderClass;
       *
       *      // register the autoloader
       *      $loader->register();
       *
       *      // register the base directories for the namespace prefix
       *      $loader->addNamespace('FooBar', '/path/to/packages/foo-bar/src');
       *      $loader->addNamespace('FooBar', '/path/to/packages/foo-bar/tests');
       *
       * The following line would cause the autoloader to attempt to load the
       * FooBarQuxQuux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
       *
       *      <?php
       *      new FooBarQuxQuux;
       *
       * The following line would cause the autoloader to attempt to load the
       * FooBarQuxQuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
       *
       *      <?php
       *      new FooBarQuxQuuxTest;
       */
      class Psr4AutoloaderClass
      {
          /**
           * An associative array where the key is a namespace prefix and the value
           * is an array of base directories for classes in that namespace.
           *
           * @var array
           */
          protected $prefixes = array();
      
          /**
           * Register loader with SPL autoloader stack.
           *
           * @return void
           */
          public function register()
          {
              spl_autoload_register(array($this, 'loadClass'));
          }
      
          /**
           * Adds a base directory for a namespace prefix.
           *
           * @param string $prefix The namespace prefix.
           * @param string $base_dir A base directory for class files in the
           * namespace.
           * @param bool $prepend If true, prepend the base directory to the stack
           * instead of appending it; this causes it to be searched first rather
           * than last.
           * @return void
           */
          public function addNamespace($prefix, $base_dir, $prepend = false)
          {
              // normalize namespace prefix
              $prefix = trim($prefix, '\') . '\';
      
              // normalize the base directory with a trailing separator
              $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . '/';
      
              // initialize the namespace prefix array
              if (isset($this->prefixes[$prefix]) === false) {
                  $this->prefixes[$prefix] = array();
              }
      
              // retain the base directory for the namespace prefix
              if ($prepend) {
                  array_unshift($this->prefixes[$prefix], $base_dir);
              } else {
                  array_push($this->prefixes[$prefix], $base_dir);
              }
          }
      
          /**
           * Loads the class file for a given class name.
           *
           * @param string $class The fully-qualified class name.
           * @return mixed The mapped file name on success, or boolean false on
           * failure.
           */
          public function loadClass($class)
          {
              // the current namespace prefix
              $prefix = $class;
      
              // work backwards through the namespace names of the fully-qualified
              // class name to find a mapped file name
              while (false !== $pos = strrpos($prefix, '\')) {
      
                  // retain the trailing namespace separator in the prefix
                  $prefix = substr($class, 0, $pos + 1);
      
                  // the rest is the relative class name
                  $relative_class = substr($class, $pos + 1);
      
                  // try to load a mapped file for the prefix and relative class
                  $mapped_file = $this->loadMappedFile($prefix, $relative_class);
                  if ($mapped_file) {
                      return $mapped_file;
                  }
      
                  // remove the trailing namespace separator for the next iteration
                  // of strrpos()
                  $prefix = rtrim($prefix, '\');
              }
      
              // never found a mapped file
              return false;
          }
      
          /**
           * Load the mapped file for a namespace prefix and relative class.
           *
           * @param string $prefix The namespace prefix.
           * @param string $relative_class The relative class name.
           * @return mixed Boolean false if no mapped file can be loaded, or the
           * name of the mapped file that was loaded.
           */
          protected function loadMappedFile($prefix, $relative_class)
          {
              // are there any base directories for this namespace prefix?
              if (isset($this->prefixes[$prefix]) === false) {
                  return false;
              }
      
              // look through base directories for this namespace prefix
              foreach ($this->prefixes[$prefix] as $base_dir) {
      
                  // replace the namespace prefix with the base directory,
                  // replace namespace separators with directory separators
                  // in the relative class name, append with .php
                  $file = $base_dir
                        . str_replace('\', '/', $relative_class)
                        . '.php';
      
                  // if the mapped file exists, require it
                  if ($this->requireFile($file)) {
                      // yes, we're done
                      return $file;
                  }
              }
      
              // never found it
              return false;
          }
      
          /**
           * If a file exists, require it from the file system.
           *
           * @param string $file The file to require.
           * @return bool True if the file exists, false if not.
           */
          protected function requireFile($file)
          {
              if (file_exists($file)) {
                  require $file;
                  return true;
              }
              return false;
          }
      }
      View Code

       单元测试:

      <?php
      namespace ExampleTests;
      
      class MockPsr4AutoloaderClass extends Psr4AutoloaderClass
      {
          protected $files = array();
      
          public function setFiles(array $files)
          {
              $this->files = $files;
          }
      
          protected function requireFile($file)
          {
              return in_array($file, $this->files);
          }
      }
      
      class Psr4AutoloaderClassTest extends PHPUnit_Framework_TestCase
      {
          protected $loader;
      
          protected function setUp()
          {
              $this->loader = new MockPsr4AutoloaderClass;
      
              $this->loader->setFiles(array(
                  '/vendor/foo.bar/src/ClassName.php',
                  '/vendor/foo.bar/src/DoomClassName.php',
                  '/vendor/foo.bar/tests/ClassNameTest.php',
                  '/vendor/foo.bardoom/src/ClassName.php',
                  '/vendor/foo.bar.baz.dib/src/ClassName.php',
                  '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php',
              ));
      
              $this->loader->addNamespace(
                  'FooBar',
                  '/vendor/foo.bar/src'
              );
      
              $this->loader->addNamespace(
                  'FooBar',
                  '/vendor/foo.bar/tests'
              );
      
              $this->loader->addNamespace(
                  'FooBarDoom',
                  '/vendor/foo.bardoom/src'
              );
      
              $this->loader->addNamespace(
                  'FooBarBazDib',
                  '/vendor/foo.bar.baz.dib/src'
              );
      
              $this->loader->addNamespace(
                  'FooBarBazDibimGir',
                  '/vendor/foo.bar.baz.dib.zim.gir/src'
              );
          }
      
          public function testExistingFile()
          {
              $actual = $this->loader->loadClass('FooBarClassName');
              $expect = '/vendor/foo.bar/src/ClassName.php';
              $this->assertSame($expect, $actual);
      
              $actual = $this->loader->loadClass('FooBarClassNameTest');
              $expect = '/vendor/foo.bar/tests/ClassNameTest.php';
              $this->assertSame($expect, $actual);
          }
      
          public function testMissingFile()
          {
              $actual = $this->loader->loadClass('No_VendorNo_PackageNoClass');
              $this->assertFalse($actual);
          }
      
          public function testDeepFile()
          {
              $actual = $this->loader->loadClass('FooBarBazDibimGirClassName');
              $expect = '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php';
              $this->assertSame($expect, $actual);
          }
      
          public function testConfusion()
          {
              $actual = $this->loader->loadClass('FooBarDoomClassName');
              $expect = '/vendor/foo.bar/src/DoomClassName.php';
              $this->assertSame($expect, $actual);
      
              $actual = $this->loader->loadClass('FooBarDoomClassName');
              $expect = '/vendor/foo.bardoom/src/ClassName.php';
              $this->assertSame($expect, $actual);
          }
      }
      View Code
      参考文献:
      1. PHP自动加载功能原理解析
      2.官网:PSR-4: Autoloader

  • 相关阅读:
    atitit。wondows 右键菜单的管理与位置存储
    Atitit mac os 版本 新特性 attilax大总结
    Atitit。木马病毒原理机密与概论以及防御
    Atitit。木马病毒原理机密与概论以及防御
    Atitit Atitit.软件兼容性原理----------API兼容 Qa7
    Atitit Atitit.软件兼容性原理----------API兼容 Qa7
    Atitit j2ee5 jee5 j2ee6 j2ee7 jee6 jee7 新特性
    Atitit j2ee5 jee5 j2ee6 j2ee7 jee6 jee7 新特性
    mysql只显示表名和备注
    phpmyadmin 在服务起上检测到错误,请查看窗口底部
  • 原文地址:https://www.cnblogs.com/jade640/p/6721370.html
Copyright © 2020-2023  润新知