Phalcon automatic loading (PHP automatic loading), phalcon loading php_PHP tutorial

Source: Internet
Author: User
Phalcon automatically loads (PHP automatically loads), and phalcon loads php. Phalcon automatic loading (PHP automatic loading), phalcon php automatic loading (phalconLoader) reprinted, please note source 1, PHP file introduced through include () or require () function, it can be automatically loaded in PH Phalcon (automatically loaded in PHP), and php can be loaded in phalcon
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__autoloadAt least three things need to be done ("Three Steps"). They are:

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:

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();

Specific implementation:

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:

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:

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:

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)

PHP auto-load (php auto-load), phalcon auto-load PHP (phalcon \ Loader) reprinted, please note source 1, php file introduced through include () or require () function, it can be found in PH...

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.