Phalcon Automatic loading (PHP automatic loading)

Source: Internet
Author: User
Tags autoload autoloader folder separator spl php class php framework throw exception zend

Auto Load (Phalcon\loader) Reprint please specify source one, PHP file introduction

The include () or require () function allows you to insert the contents of a file into the file before the PHP program executes.

Difference: The way the error is handled differs . The include () function generates a warning (but the script continues to execute), and the require () function generates a fatal error (fatal Error) (the script will stop executing after the bug has occurred)

* The script does not continue because the file does not exist or is renamed, so we recommend using require () instead of include ().

Second, the PHP class automatically loaded

Reference article: PHP Manual and PHP class auto-loading mechanism

Before the PHP5, each PHP framework implements the loading of the class, generally to implement a traversal directory According to a certain convention, automatically load the file class or function that conforms to the contract condition. Thus the use of classes before PHP5 is not frequent now.

After php5, the Zend engine calls the __autoload function automatically when the PHP class is loaded, if the folder in which the class is located is not included or if the class name is wrong. The __autoload function needs to be implemented by the user itself.

After the php5.1.2 version, you can use the spl_autoload_register function to customize the load handler function. When this function is not called, the SPL custom spl_autoload function is used by default.

1. PHP Automatic loading of __autoload

 function  __autoload ( $className  Span style= "color: #000000;" ) {  $file  =  $className .    '. php ' ;  if  (is_file  ( $file   require  ( $file  );  else  { echo  ' no this '.  $className .    ' class file ' ; }}   $demo  = new  demo (); 

In fact, we can see __autoload at least three things to do (" three Steps "), respectively:

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

In the first and second steps, we have to contract the method of mapping the class name to the file, so that we can find its corresponding file according to the class name and implement the loading.

Therefore, in __autoload automatic loading, the most important thing is to specify the corresponding relationship between the class name and the file in which it resides . When a large number of classes need to be included, we only need to establish the appropriate rules , and then the class name and its corresponding file mapping , it is possible to implement lazy loading (lazy loading) .

Tip:spl_autoload_register () provides a more flexible way to implement automatic loading of classes. Therefore, it is no longer recommended to use the __autoload () function, which may be deprecated in later versions.

2. PHP Automatic loading of Spl_autoload_register

Introduction: If in a PHP system implementation, a lot of other class libraries are used, these libraries may have been developed by different engineers, so the class name and the file in which the mapping rules are not the same. At this point, if you want to implement the automatic loading of the class library, all the mapping rules must be implemented in the __autoload function. This can cause __autoload to be very complex and even impossible to implement. It also makes the __autoload function very bloated. has a significant negative impact on future system maintenance and performance. (disadvantages of __autoload )


Registers the given function as an implementation of the __autoload. In short, it is the __autoload function stack that registers the function with the SPL, and removes the default __autload () function of the system.

function __autoload ($className) {      echo$className, ' <br/> ' ;  }   function classLoader ($className) {      echo$className, ' <br/> ';  }  Spl_autoload_register (' ClassLoader ');   New Test (); //


  1. If you have implemented the __autoload () function in your program, it must be explicitly registered in the __autoload () queue. Because the Spl_autoload_register () function replaces the __autoload () function in Zend Engine with spl_autoload () or Spl_autoload_call ().
  2. Can only be defined once compared to __autoload. The Spl_autoload_register () function can define multiple autoload functions . Because Spl_autoload_register creates a AutoLoad function queue, the queue is executed one by one in the order defined.

     function __autoload($className) {       echo ‘autload class:‘ . $className . ‘<br />‘;   }   function classLoader($className) {       echo ‘SPL load class:‘ . $className . ‘<br />‘;   }   spl_autoload_register(‘classLoader‘);   $demo = new Demo();//结果:SPL load class:Demo
Function description
bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
    • Autoload_function "optional" function added to the auto-load stack. The default 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 '), it makes it possible to use an object's method .
    • Throw exception if "optional" fails to register successfully
    • Prepend "Optional" will add the function to the top of the queue, not the tail of the queue.

remark: The SPL auto-load function is provided by Spl_autoload (), Spl_autoload_register (), Spl_autoload_functions (), Spl_autoload_extensions () and Spl_ Provided by the Autoload_call () function.

Third, the class of Phalcon automatic loading

Phalcon\loader Universal ClassLoader (Universal class Loader), designed to automatically load classes in projects based on protocol help projects (this component helps to load your project classes Autom Atically based on some conventions). The Phalcon supports four kinds of loading methods, namely, registering the class name, registering the namespace, registering the prefix, and registering the folder.

Phalcon default file suffix is PHP, of course you can also configure (Setextensions ()).

1. Register class name
<? PHP $loader New \phalcon\loader (); registerclasses (    array(        "Some" = "library/"), $loader         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. The fastest automatic method
    2. Not conducive to maintenance

Specific implementation:

  1. Determines whether a class is registered.
  2. Determines whether the class that needs to be loaded is registered and loads its corresponding path file if it is already registered.
2. Registering namespaces
<? PHP $loader New \phalcon\loader ();     registernamespaces (array(       "example\base" and "=") $loader    vendor/example/base/",       " example\adapter "=" vendor/example/adapter/",       " Example "and"         vendor/" example/",    )); $loader, register (); // vendor/example/adapter/some.php $some New Example\adapter\some ();

When you use a namespace or an external library to organize your code, you can automatically load the libraries it contains by registering the namespace.

For a namespace-corresponding path, add a slash to the end of it.

Specific implementation:

  1. Determines whether a namespace is registered.
  2. Determines whether the class that needs to be loaded starts with a registered name.

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

    "Example\base"    $test 1new example\base\test ();   vendor/example/base/test.php$test 2new example\test (); // error, unable to load. 

    Name processing: 1, remove the name of the specified space prefix. 2. Convert namespace separators to \ file separators/

  3. Build the full file path based on the file extension, and determine if the file exists, such as the file exists loaded.
3. Registration Prefix
<? PHP $loader New \phalcon\loader ();     registerprefixes (array(       "example_base" and "=") $loader     vendor/example/base/",       " example_adapter "  =" vendor/example/adapter/",       " Example_ "and"         = " vendor/example/",    ));     $loader, register ();     // vendor/example/adapter/some.php $some New Example_adapter_some ();

Similar to namespaces, Phalcon will no longer support prefixes starting with 2.1.0.

Specific implementation:

  1. Determine if a prefix is registered.
  2. Determines whether the class that needs to be loaded has been named before the prefix.

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

    "Example_base"    $test 1new example_base_test ();   vendor/example/base/test.php$test 2new example_test (); // error, unable to load. 

    Name processing: 1, remove the prefix of the class. 2. Convert prefix delimiter to _ file delimiter/

  3. Build the full file path based on the file extension, and determine if the file exists, such as the file exists loaded.
4. Registering a folder
<? PHP $loader New \phalcon\loader ();     $loader-registerdirs (    array(        "library/mycomponent/",        " library/othercomponent/other/",        " vendor/example/adapters/",        " vendor/example/"    ));     $loader, register ();     // i.e. library/othercomponent/other/some.php $some New Some ();

The class file under the registered directory can be loaded automatically. However, this approach is not recommended in terms of performance because Phalcon will look for files with the same class name in a large number of folders. When using the registration directory for automatic loading, be aware of the dependencies of the registered directory and put the important directories ahead.

Specific implementation:

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

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

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

5. Modify current policy (modifying strategies)

Adds additional values for the current auto-loading data.

<? PHP // Adding More Directories $loader-registerdirs (    array(        ". /app/library/",        ". /app/plugins/"    ),    true);

When registering, add the second parameter value true so that it merges with the original array.

6. Security Layer

There are no security checks for the autoloader, as follows:

<? PHP // Basic autoloaderspl_autoload_register (function($className) {    if (file_exists($className . '. php ') {        require$className . '. php ';    }});

If we do not have any security checks, if the autoloader is accidentally restarted, then the maliciously prepared string is returned to the important file in the program as a parameter.

<? PHP // This variable isn't filtered and comes from an insecure source $className = '. /processes/important-process '; // Check if the class exists triggering the Auto-loader if (class_exists($className)) {    //...}

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

7. Auto-load Events

In the following example, instead of using the ClassLoader, we get the process operation for debugging information:

<?PHP$eventsManager=New\phalcon\events\manager ();$loader=New\phalcon\loader ();$loader->registernamespaces (Array(       ' Example\\base ' = ' vendor/example/base/', ' example\\adapter ' = ' vendor/example/adapter/', ' Example ' =& Gt ' 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 ();

Phalcon Auto-Load supports the following events:

    • Beforecheckclass, the automatic loading process starts before triggering, and when returning a Boolean dummy can stop the active operation.
    • Pathfound, when a class loader is positioned to trigger
    • Aftercheckclass, the automatic loading process is completed and triggered.
8. Precautions (troubleshooting)
    1. Automatic loading is case sensitive.
    2. Namespaces or prefixes are much faster than the way folders are.

Phalcon Automatic loading (PHP automatic loading)

Related Article

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: 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.