PHP PSR-0 standards using namespace for autoloading-php Tutorial

Source: Internet
Author: User
Tags spl
Before using namespace for autoloading to introduce PSR-0, let's talk about NameSpace and Autoloading.

NameSpace)

Namespace is a new feature added to PHP5.3. it is used to solve the two problems encountered when you create reusable code such as classes or functions when writing a class library or application:

1. the user-written code conflicts with the names of PHP internal classes/functions/constants or third-party classes/functions/constants.
2. create an alias (or short) name for a long identifier name (usually defined to mitigate the first type of problem) to improve the readability of the source code.

Elements in the PHP namespace use a file system-like principle. For example, a class name can be referenced in three ways:
1. a non-qualified name or a class name without a prefix, for example, $ a = new foo (); or foo: staticmethod ();. If the current namespace is currentnamespace, foo will be parsed as currentnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as foo. Warning if the function or constant in the namespace is not defined, the undefined function name or constant name will be resolved to the global function name or constant name. For more information, see use namespace: backup global function name/constant name.
2. a qualified name or prefix name, for example, $ a = new subnamespace \ foo (); or subnamespace \ foo: staticmethod ();. If the current namespace is currentnamespace, foo will be parsed as currentnamespace \ subnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as subnamespace \ foo.
3. fully qualified names, or names that contain Global prefix operators, such as $ a = new \ currentnamespace \ foo (); or \ currentnamespace \ foo: staticmethod ();. In this case, foo is always parsed as the text name (literal name) currentnamespace \ foo in the code.

In addition, you can use a fully qualified name to access any global class, function, or constant, for example, \ strlen (), \ Exception, or \ INI_ALL.

 

The above is a brief introduction to namespace. if you do not know this, read the document carefully. Namespace has been widely used in many new PHP projects. Especially with the popularity of Composer, it is necessary to understand the features.


Autoloading)

Many developers create a PHP source file for each class definition when writing object-oriented applications. A major headache is that you have to write a long list of include files (one file for each class) at the beginning of each script ).

While Autoloading solves this problem. by defining a/series autoload function, it will automatically call it when trying to use a class that has not been defined. By calling the autoload function, the script engine has the last chance to load the required class before a PHP error fails. The autoload function can be the default _ autoload (), as follows:

 You can also use a more flexible method to define our own _ autoload () function through spl_autoload_register:

  The above code registers the my_autoload () function to the _ autoload stack, so that the _ autoload () function (_ autoload () function no longer works, but it can be explicitly registered to the _ autoload stack ). Note that we mentioned the _ autoload stack just now, which means we can register multiple autoload functions and load them in sequence according to the registration order (this order can be changed through the third parameter of spl_autoload_register ).

Here we show the simplest example of the autoload function. of course, through some rule settings, it can also be competent for many complex situations in the actual environment.

However, if our project depends on some other projects, we can run smoothly under their independent loading rules, but the integration may be bad. Can there be a general loading rule to solve this problem?

PSR-0

This is a series of standards/specifications released by the PHP Framework Interoperability Group (PHP universal Framework Group), which currently includes PSR-0 ~ PSR-4 is a total of 4, and the PSR-0 is one of the automatic loading standards (the subsequent PSR-4 called improved automatic loading standards, is a supplement to the PSR-0. PSR-0 is more widely used ). Https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

The following describes the conditions required for automatic loading of specific interoperability:

Mandatory

  • A fully qualified namespace and class must conform to this structure \ \( \)*
  • Each namespace must have a top-level namespace ("Vendor Name" Provider Name)
  • Each namespace can have multiple sub-namespaces
  • When loading from a file system, the separator of each namespace must be converted to DIRECTORY_SEPARATOR (operating system path separator)
  • In class name, each underscore (_) must be converted to DIRECTORY_SEPARATOR. In namespace, the underscore (_) has no (special) meaning.
  • When loading from the file system, the qualified namespace and class must end with. php
  • Verdorname, namespaces, and class names can be composed of uppercase and lowercase letters (case sensitive)
  • This rule may also be followed: If the file does not exist, false is returned.


    Example

  • \ Doctrine \ Common \ IsolatedClassLoader =>/path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader. php
  • \ Symfony \ Core \ Request =>/path/to/project/lib/vendor/Symfony/Core/Request. php
  • \ Zend \ Acl =>/path/to/project/lib/vendor/Zend/Acl. php
  • \ Zend \ Mail \ Message =>/path/to/project/lib/vendor/Zend/Mail/Message. php
  • Underline in NameSpace and Class Name

  • \ Namespace \ package \ Class_Name =>/path/to/project/lib/vendor/namespace/package/Class/Name. php
  • \ Namespace \ package_name \ Class_Name =>/path/to/project/lib/vendor/namespace/package_name/Class/Name. php
  • Implementation example

    Below is a simple example of automatic loading according to the above standard:

         

    Implementation of SplClassLoader

    Below is an implementation example of SplClassLoader. if you follow the above standard, you can use it for automatic loading. This is also the currently recommended class loading standard for PHP5.3. Http://gist.github.com/221634

        register(); * * @license http://www.opensource.org/licenses/mit-license.html  MIT License * @author Jonathan H. Wage 
        
          * @author Roman S. Borschel 
         
           * @author Matthew Weier O'Phinney 
          
            * @author Kris Wallsmith 
           
             * @author Fabien Potencier 
            
              */class SplClassLoader{    private $_fileExtension = '.php';    private $_namespace;    private $_includePath;    private $_namespaceSeparator = '\\';     /**     * Creates a new 
             SplClassLoader that loads classes of the     * specified namespace.     *      * @param string $ns The namespace to use.     */    public function __construct($ns = null, $includePath = null)    {        $this->_namespace = $ns;        $this->_includePath = $includePath;    }     /**     * Sets the namespace separator used by classes in the namespace of this class loader.     *      * @param string $sep The separator to use.     */    public function setNamespaceSeparator($sep)    {        $this->_namespaceSeparator = $sep;    }     /**     * Gets the namespace seperator used by classes in the namespace of this class loader.     *     * @return void     */    public function getNamespaceSeparator()    {        return $this->_namespaceSeparator;    }     /**     * Sets the base include path for all class files in the namespace of this class loader.     *      * @param string $includePath     */    public function setIncludePath($includePath)    {        $this->_includePath = $includePath;    }     /**     * Gets the base include path for all class files in the namespace of this class loader.     *     * @return string $includePath     */    public function getIncludePath()    {        return $this->_includePath;    }     /**     * Sets the file extension of class files in the namespace of this class loader.     *      * @param string $fileExtension     */    public function setFileExtension($fileExtension)    {        $this->_fileExtension = $fileExtension;    }     /**     * Gets the file extension of class files in the namespace of this class loader.     *     * @return string $fileExtension     */    public function getFileExtension()    {        return $this->_fileExtension;    }     /**     * Installs this class loader on the SPL autoload stack.     */    public function register()    {        spl_autoload_register(array($this, 'loadClass'));    }     /**     * Uninstalls this class loader from the SPL autoloader stack.     */    public function unregister()    {        spl_autoload_unregister(array($this, 'loadClass'));    }     /**     * Loads the given class or interface.     *     * @param string $className The name of the class to load.     * @return void     */    public function loadClass($className)    {        if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) {            $fileName = '';            $namespace = '';            if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) {                $namespace = substr($className, 0, $lastNsPos);                $className = substr($className, $lastNsPos + 1);                $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;            }            $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension;             require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName;        }    }}
            
           
          
         
        

    .

    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.