本文只是對PSR中的overview的摘錄,不足以覆蓋推薦標準的所有內容。具體細節參考官網,或PSR編碼規範(中文版)。其中,中文版對官網的規範進行了翻譯,便於閱讀。可是用例方面,雖然也是複製自官網用例,可是用例的格式已經發生錯誤,用例應該參考官網。php
上述標準中,第三條比較費解。更進一步的解釋以下:"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."git
Files MUST use only
<?php
and<?=
tags.githubFiles MUST use only UTF-8 without BOM for PHP code.web
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.thinkphp
Namespaces and classes MUST follow an 「autoloading」 PSR: [PSR-0, PSR-4].segmentfault
Class names MUST be declared in
StudlyCaps
.appClass constants MUST be declared in all upper case with underscore separators.less
Method names MUST be declared in
camelCase
.ide
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
"side effect"不可以被理解成「反作用」而應該是「附做用」,是指執行了和「declaring classes, functions, constants, etc」 不直接關聯的邏輯執行操做。換言之,就是要把申明和執行分開,放在不一樣的文件中,那些申明經過include、require導入。require
orinclude
, 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.
例如:
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 ofuse
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
andfinal
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 Vendor\Package; 3 4 use FooInterface; 5 use BarClass as Bar; 6 use OtherVendor\OtherPackage\BazClass; 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 }
PSR4標準與PSR0標準的區別:規範以下:
1. 在類名中使用下劃線沒有任何特殊含義。
2. 命名空間與文件目錄的映射方法有所調整
例子:
The term 「class」 refers to classes, interfaces, traits, and other similar structures.
A fully qualified class name has the following form:
\<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>
The fully qualified class name MUST have a top-level namespace name, also known as a 「vendor namespace」.
The fully qualified class name MAY have one or more sub-namespace names.
The fully qualified class name MUST have a terminating class name.
Underscores have no special meaning in any portion of the fully qualified class name. //與PSR-0的差異,PSR-0會將‘_’替換爲directory separator
Alphabetic characters in the fully qualified class name MAY be any combination of lower case and upper case.
All class names MUST be referenced in a case-sensitive fashion.
When loading a file that corresponds to a fully qualified class name …
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,見下方代碼中的例子。
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下的子目錄
The terminating class name corresponds to a file name ending in
.php
. The file name MUST match the case of the terminating class name.Autoloader implementations MUST NOT throw exceptions, MUST NOT raise errors of any level, and SHOULD NOT return a value.
Fully Qualified Class Name | Namespace Prefix | Base Directory | Resulting File Path |
---|---|---|---|
\Acme\Log\Writer\File_Writer | Acme\Log\Writer | ./acme-log-writer/lib/ | ./acme-log-writer/lib/File_Writer.php |
\Aura\Web\Response\Status | Aura\Web | /path/to/aura-web/src/ | /path/to/aura-web/src/Response/Status.php |
\Symfony\Core\Request | Symfony\Core | ./vendor/Symfony/Core/ | ./vendor/Symfony/Core/Request.php |
\Zend\Acl | 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 # Foo\Bar\Baz * Qux/ * Quux.php # Foo\Bar\Qux\Quux * tests/ * BazTest.php # Foo\Bar\BazTest * Qux/ * QuuxTest.php # Foo\Bar\Qux\QuuxTest * * ... add the path to the class files for the \Foo\Bar\ namespace prefix * as follows: * * <?php * // instantiate the loader * $loader = new \Example\Psr4AutoloaderClass; * * // register the autoloader * $loader->register(); * * // register the base directories for the namespace prefix * $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src'); * $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/tests'); * * The following line would cause the autoloader to attempt to load the * \Foo\Bar\Qux\Quux class from /path/to/packages/foo-bar/src/Qux/Quux.php: * * <?php * new \Foo\Bar\Qux\Quux; * * The following line would cause the autoloader to attempt to load the * \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php: * * <?php * new \Foo\Bar\Qux\QuuxTest; */ 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; } }
單元測試:
<?php namespace Example\Tests; 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( 'Foo\Bar', '/vendor/foo.bar/src' ); $this->loader->addNamespace( 'Foo\Bar', '/vendor/foo.bar/tests' ); $this->loader->addNamespace( 'Foo\BarDoom', '/vendor/foo.bardoom/src' ); $this->loader->addNamespace( 'Foo\Bar\Baz\Dib', '/vendor/foo.bar.baz.dib/src' ); $this->loader->addNamespace( 'Foo\Bar\Baz\Dib\Zim\Gir', '/vendor/foo.bar.baz.dib.zim.gir/src' ); } public function testExistingFile() { $actual = $this->loader->loadClass('Foo\Bar\ClassName'); $expect = '/vendor/foo.bar/src/ClassName.php'; $this->assertSame($expect, $actual); $actual = $this->loader->loadClass('Foo\Bar\ClassNameTest'); $expect = '/vendor/foo.bar/tests/ClassNameTest.php'; $this->assertSame($expect, $actual); } public function testMissingFile() { $actual = $this->loader->loadClass('No_Vendor\No_Package\NoClass'); $this->assertFalse($actual); } public function testDeepFile() { $actual = $this->loader->loadClass('Foo\Bar\Baz\Dib\Zim\Gir\ClassName'); $expect = '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php'; $this->assertSame($expect, $actual); } public function testConfusion() { $actual = $this->loader->loadClass('Foo\Bar\DoomClassName'); $expect = '/vendor/foo.bar/src/DoomClassName.php'; $this->assertSame($expect, $actual); $actual = $this->loader->loadClass('Foo\BarDoom\ClassName'); $expect = '/vendor/foo.bardoom/src/ClassName.php'; $this->assertSame($expect, $actual); } }
參考文獻: