Phalcon automatic loading (PHP auto load), Phalcon loading php_php tutorial

Source: Internet
Author: User
Tags autoloader spl php framework throw exception

Phalcon Automatic loading (PHP automatic loading), Phalcon loading PHP


Auto Load (Phalcon\loader)

Reprint please indicate source

First, the introduction of PHP files

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 that the require () function generates a fatal error (fatal error) (the script will stop executing after the errors have 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) {    $file$className . '. php ';     if (is_file($file)) {        require($file);    } Else {        echo$className . ' class file ';    }} $demo New Demo ();

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

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 )

Spl_autoload_register:

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, '
'; } function classLoader ($className) { echo$className, '
'; } Spl_autoload_register (' ClassLoader '); New Test (); //

TIP:

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$loadernew  \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 ();

Specific implementation:

2. Registering namespaces

 
  PHP$loadernew  \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:

3. Registration Prefix

 
  PHP$loadernew  \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:

4. Registering a folder

 
  PHP$loadernew  \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:

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 aninsecure 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$eventsManagernew  \phalcon\events\manager (); $loader New \phalcon\loader (); $loader->registernamespaces (array(       ' example\\base ' = ' vendor/example/') base/',       ' example\\adapter ' = ' vendor/example/adapter/',       ' Example ' = ' vendor/example/'); // Listen all the loader events $eventsManager 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)

http://www.bkjia.com/PHPjc/1092699.html www.bkjia.com true http://www.bkjia.com/PHPjc/1092699.html techarticle Phalcon automatic loading (PHP automatic loading), Phalcon load PHP automatic loading (phalcon\loader) Reprint please specify source one, PHP file introduced via include () or require () function, can be in ph ...

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