[PHP series] PHP recommended standard PSR-4, automatic loader policy, phppsr-4

Source: Internet
Author: User
Tags autoloader traits

[PHP series] PHP recommended standard PSR-4, automatic loader policy, phppsr-4

The last time we talked about the PSR-3 logger interface, this time we're talking about the last standard of the SRS, The PSR-4, the auto loader policy.

Reason

The auto-loader policy refers to finding and loading PHP classes, interfaces, or traits as needed during runtime.

Supports standard PHP components and frameworks for PSR-4 auto-loaders, using the same auto-loader to find the code and then load it into the PHP interpreter.

You may often see the following code when you look at the PHP code.

<?phpinclude 'path/to/file1.php';include 'path/to/file2.php';include 'path/to/file3.php';

If you need to introduce one hundred and one thousand PHP scripts, the include () function will not be competent. With the automatic loader, we don't need to introduce files like this. The automatic loader policy can find PHP classes, interfaces, or traits, and then load them into the PHP interpreter as needed during runtime.

Most modern PHP components and frameworks comply with PSR-4 specifications, and if you want to write and distribute PHP components yourself, make sure that your components also comply with PSR-4 specifications.

PSR-4

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>

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.

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.

3. When loading a file that corresponds to a fully qualified class name... (Load the complete path 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 ".

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.

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 except tions, must not raise errors of any level, and shocould NOT return a value.

Example
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

The essence of PSR-4 is to map the namespace prefix to the directory in the file system. For example, I can tell PHP that the classes, interfaces, and traits in the \ Feng \ YePHP namespace are in the src/directory of the physical file system, so that PHP can know, the classes, interfaces, and traits in the namespace prefixed with \ Feng \ YePHP correspond to directories and files in the src/directory.

How to compile
<?php/** * An example of a project-specific implementation. *  * After registering this autoload function with SPL, the following line * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class * from /path/to/project/src/Baz/Qux.php: *  *      new \Foo\Bar\Baz\Qux; *       * @param string $class The fully-qualified class name. * @return void */spl_autoload_register(function ($class) {    // project-specific namespace prefix    $prefix = 'Foo\\Bar\\';    // base directory for the namespace prefix    $base_dir = __DIR__ . '/src/';    // does the class use the namespace prefix?    $len = strlen($prefix);    if (strncmp($prefix, $class, $len) !== 0) {        // no, move to the next registered autoloader        return;    }    // get the relative class name    $relative_class = substr($class, $len);    // 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 file exists, require it    if (file_exists($file)) {        require $file;    }});

Copy the above Code, paste it into your application, and then modify the values of the variable $ prefix and $ base_dir so that you can have an available PSR-4 auto loader.

But you don't have to do that because we can use the PSR-4 auto loader that is automatically generated by the dependency manager Composer. We will refer to this Composer in subsequent blog posts.

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.