Phalcon automatic loading (PHP automatic loading)

Source: Internet
Author: User
Tags file separator spl
Phalcon automatic loading (PHP automatic loading) automatic loading (phalcon \ Loader) reprinted please indicate source 1. PHP file introduction

Using the include () or require () function, you can insert the content of a file into the file before the PHP program is executed.

Difference: The error handling method is different.Include () functionsAWarning(But the script will continue to be executed), andRequire ()The function generatesFatal error(Fatal error) (execution stops when an error occurs)

* Because the script is not executed after the file does not exist or is renamed, we recommend that you use require () instead of include ().

II. php class automatic loading

Reference: php Manual and PHP class automatic loading mechanism

Before php5, php frameworks generally implement class loading by traversing directories according to certain conventions, and automatically load file classes or functions that meet the specified conditions. Therefore, classes were not frequently used before php5.

After php5, when the php class is loaded, the Zend Engine automatically calls_ Autoload function. The _ autoload function must be implemented by the user.

After php5.1.2, you can useSpl_autoload_register functionCustom Loading handler. If this function is not called, the spl_autoload function customized by spl is used by default.

1. php autoload
function __autoload($className) {    $file = $className . '.php';    if (is_file($file)) {        require($file);    }else{        echo 'no this ' . $className . ' class file';    }}$demo = new Demo();

In fact, we can see that _ autoload requires at least three things ("Three Steps"). They are:

  1. Determine the file name of the class based on the class name.
  2. Determine the path of the class file. in the above example, relative positioning is used. our test file is actually in the same directory.
  3. Load the file containing the specified class to the program.

In step 1 and Step 2, we must specify the class name and fileIng methodOnly in this way can we find the corresponding file based on the class name and load it.

Therefore, the most important part in _ autoload automatic loading isCorrespondence between the specified class name and its file. When a large number of classes need to be included, we only need to establish the corresponding rules and map the class names to their corresponding files.Lazy loading).

Tip: spl_autoload_register () provides a more flexible way to automatically load classes. Therefore, it is no longer recommended to use the _ autoload () function, which may be discarded in future versions.

2. spl_autoload_register for php automatic loading

Introduction: if many other class libraries are used in a php system implementation, these class libraries may be developed by different engineers, therefore, the ing rules of the class name and the file are different. In this case, to automatically load the class library, you must implement all the ing rules in the _ autoload function. This will cause _ autoload to be very complicated and even unable to be implemented. It also makes the _ autoload function very bloated. It has a huge negative impact on system maintenance and performance in the future. (_ Disadvantages of autoload)

Spl_autoload_register:

Register the given function as the implementation of _ autoload. Simply put, it is to register the function in the SPL's _ autoload function stack and remove the system's default _ autload () function.

Function _ autoload ($ className) {echo 'autload class: ', $ className ,'
';} Function classLoader ($ className) {echo 'SPL load class:', $ className ,'
';} Spl_autoload_register ('classloader'); new Test (); // Result: SPL load class: Test

Tip:

  1. If the _ autoload () function has been implemented in your program, it mustExplicit registrationTo the _ autoload () queue. Because the spl_autoload_register () function replaces the _ autoload () function in Zend Engine with spl_autoload () or spl_autoload_call ().
  2. Compared with _ autoload, this parameter can be defined only once. The spl_autoload_register () function is optional.Define multiple autoload functions. Because spl_autoload_register creates an autoload function queue, this queue is executed one by one according to the defined sequence.

    Function _ autoload ($ className) {echo 'autload class: '. $ className .'
    ';} Function classLoader ($ className) {echo 'SPL load class:'. $ className .'
    ';} Spl_autoload_register ('classloader'); $ demo = new Demo (); // Result: SPL load class: Demo

Function description

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

  • Autoload_function [optional] function used to automatically load stacks. The default value is spl_autoload ().
    • You can also call the spl_autoload_register () function to register a callback function, instead of providing a String name for the function. If you provide an array such as array ('class', 'method'), you canHow to use an object.
  • Throw [optional] whether to throw an exception when the registration fails.
  • Prepend [optional] whether to add the function to the first of the queue, rather than the end of the queue.

Note: The SPL automatic loading function is provided by the spl_autoload (), spl_autoload_register (), spl_autoload_functions (), spl_autoload_extensions (), and spl_autoload_call () functions.

III. Automatic loading of Phalcon classes

Phalcon \ Loader Universal Class Loader is intended to help the project automatically load classes in the project according to the protocol (This component helps to load your project classes automatically based on some conventions ). Phalcon supports four loading modes: registration class name, registration namespace, registration prefix, and registration folder.

The default file suffix of Phalcon is php. you can also configure (setExtensions () by yourself ()).

1. registration class name
 registerClasses(    array(        "Some"         => "library/OtherComponent/Other/Some.php",        "Example\Base" => "vendor/example/adapters/Example/BaseClass.php",    ));$loader->register();    // i.e. library/OtherComponent/Other/Some.php$some = new Some();
  1. Fastest Automatic method
  2. Not conducive to maintenance

Specific implementation:

  1. Determine whether a class is registered.
  2. Determine whether the class to be loaded is registered. if it is registered, load the corresponding path file.

2. Register a namespace
 registerNamespaces(    array(       "Example\Base"    => "vendor/example/base/",       "Example\Adapter" => "vendor/example/adapter/",       "Example"         => "vendor/example/",    ));$loader->register();// vendor/example/adapter/Some.php$some = new Example\Adapter\Some();

When using a namespace or external library to organize code, you can use the registration namespace method to automatically load the library it contains.

Add a slash to the end of the path corresponding to the namespace.

Specific implementation:

  1. Determine whether a namespace is registered.
  2. Determine whether the class to be loaded has started with the registered name.

    For Example, the registered namespace is "example \ Base" => "vendor/Example/base /"

    "Example \ Base" => "vendor/example/base/" $ test1 = new Example \ Base \ Test (); // vendor/example/base/Test. php $ test2 = new Example \ Test (); // error, unable to load.

    Name processing: 1. remove the specified namespace prefix. 2. convert the namespace separator \ to the File Separator/

  3. Build a complete file path based on the file extension name and determine whether the file exists. if the file is loaded.

3. Register the prefix
 registerPrefixes(    array(       "Example_Base"     => "vendor/example/base/",       "Example_Adapter"  => "vendor/example/adapter/",       "Example_"         => "vendor/example/",    ));    $loader->register();    // vendor/example/adapter/Some.php$some = new Example_Adapter_Some();

Like a namespace, phalcon no longer supports prefixes starting from 2.1.0.

Specific implementation:

  1. Determine whether a prefix is registered.
  2. Determine whether the class to be loaded is named after the previous fix.

    For example, the registered prefix is "Example_Base" => "vendor/example/base /"

    "Example_Base" => "vendor/example/base/" $ test1 = new Example_Base_Test (); // vendor/example/base/Test. php $ test2 = new Example_Test (); // error, unable to load.

    Name processing: 1. remove the class prefix. 2. convert the prefix delimiter _ into a file separator/

  3. Build a complete file path based on the file extension name and determine whether the file exists. if the file is loaded.

4. Register a folder
 registerDirs(    array(        "library/MyComponent/",        "library/OtherComponent/Other/",        "vendor/example/adapters/",        "vendor/example/"    ));    $loader->register();    // i.e. library/OtherComponent/Other/Some.php$some = new Some();

Class files under the registration directory can be automatically loaded. However, this method is not recommended in terms of performance, because Phalcon will find a large number of files with the same class name in a folder. When using the registered directory to automatically load, pay attention to the relevance of the registered directory, that is, put important directories in front.

Specific implementation:

  1. Replace prefix separator _ or namespace separator \ in the class name with a folder delimiter/
  2. Check whether a folder is registered.
  3. Build possible file paths based on the file suffix

    For example, the registered prefix is "vendor/example/base /"

     $test = new Test();// vendor/example/base/Test.php

5. modify the current policy (Modifying current strategies)

Add additional values for the currently automatically loaded data.

 registerDirs(    array(        "../app/library/",        "../app/plugins/"    ),    true);

Add the second parameter value "true" during registration so that it can be combined with the original number.

6. Security Layer)

There is no automatic loader for any security check, as shown below:

     

If the automatic loader is enabled without any security check, the strings that are maliciously prepared are returned as parameters to access important files in the program.

      

Phalcon's approach is to delete any useless strings and reduce the possibility of being attacked.

7. automatically load events

In the following example, you do not need to use the class loader to obtain debugging information:

   registerNamespaces(array(       'Example\\Base' => 'vendor/example/base/',       'Example\\Adapter' => 'vendor/example/adapter/',       'Example' => 'vendor/example/'));//Listen all the loader events$eventsManager->attach('loader', function($event, $loader) {    if ($event->getType() == 'beforeCheckPath') {        echo $loader->getCheckedPath();    }});$loader->setEventsManager($eventsManager);$loader->register();

Automatic Phalcon loading supports the following events:

  • BeforeCheckClass, triggered before the automatic loading process starts. when boolean false is returned, the activity can be stopped.
  • PathFound, triggered when a class loader is located
  • AfterCheckClass, triggered after the automatic loading process is completed.
8. notes (Troubleshooting)
  1. Auto load is case sensitive.
  2. The namespace or prefix method is much faster than the folder method.

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.