PHP Management Dependency (dependency) Relationship Tool Composer Auto-load (autoload), dependencyautoload_php tutorial

Source: Internet
Author: User
Tags autoload autoloader

PHP Management Dependency (dependency) Relationship Tool Composer Auto-load (autoload), dependencyautoload


For example, assuming that our project wants to use the Monolog log tool, we need to tell composer in Composer.json that we need it:

{"Require": {  "Monolog/monolog": "1.*"}}

After execution:

PHP Composer.phar Install

OK, now that the installation is done, how to use it? Composer automatically generates a AutoLoad file, you just need to reference it

Require '/path/to/vendor/autoload.php ';

Then can be very convenient to use the third-party class library, is not feeling great ah! For the monolog we need, it can be used:

Use Monolog\logger;use monolog\handler\streamhandler;//Create a log channel$log = new Logger (' name '); $log Pushhandler (New Streamhandler ('/path/to/log/log_name.log ', logger::warning));//Add records to the log$log-> Addwarning (' Foo '); $log->adderror (' Bar ');

What did composer do in the process? It generates a autoloader and then configures it according to each package's own autoload, which helps us to do the work of automatic loading. (If you don't know anything about this part of AutoLoad, you can read one of my previous articles
Next, let's see how composer is doing it.

For the automatic loading of third-party packages, composer provides four ways of support, namely PSR-0 and PSR-4 automatic loading (I've also introduced them in an article), generating Class-map, and the way directly containing files.

PSR-4 is a recommended approach for composer because it is easier to use and provides a cleaner directory structure. This is configured in Composer.json:

{"AutoLoad": {"    psr-4": {      "foo\\": "src/",    }}  }

Key and value define the namespace and mapping to the corresponding path. In accordance with the PSR-4 rule, when attempting to automatically load the class "Foo\\bar\\baz", it will look for the "src/bar/baz.php" file and load it if it exists. Note that the "foo\\"
Does not appear in the file path, which is different from PSR-0, if PSR-0 has this configuration, then will go to find

"Src/foo/bar/baz.php"

This file.

Also note that in the configuration of PSR-4 and PSR-0, the namespace delimiter at the end of "foo\\" must be added and escaped in case "Foo" matches to an unexpected occurrence such as "FooBar".

After the composer is installed or updated, the configuration of psr-4 is converted to the form of a map namespace Key,dir path as value and written to the generated vendor/composer/autoload_psr4.php file.

{"AutoLoad": {"    psr-0": {      "foo\\": "src/",    }}  }

Finally, this configuration is also written in the form of map to the generated

vendor/composer/autoload_namespaces.php

File.

Class-map is done by configuring the specified directory or file, and then when the composer is installed or updated, it scans the class in a file in the specified directory that ends in. php or. Inc, generates a map of class to the specified file path, and joins the newly generated vendor/composer/autoload_classmap.php file,.

{"  autoload": {    "classmap": ["src/", "lib/", "something.php"]  }}

For example, there is a Basecontroller class under src/, so the configuration is generated in the autoload_classmap.php file:

' Basecontroller ' = $baseDir. '/src/basecontroller.php '

The files method is to manually specify the file to be loaded directly. For example, we have a series of global helper functions that can be put into a helper file and then loaded directly

{"  AutoLoad": {"    files": ["src/mylibrary/functions.php"]  }}

It generates an array containing the files specified in these configurations, and then writes the newly generated

vendor/composer/autoload_files.php

File for Autoloader to load directly.

Let's take a look at composer AutoLoad's code.

<?php//autoload_real.php @generated by Composerclass composerautoloaderinit73612b48e6c3d0de8d56e03dece61d11{  private static $loader; public static function Loadclassloader ($class) {if (' composer\autoload\classloader ' = = = $class) {require __dir__. '/classloader.php '; }} public static function Getloader () {if (Null!== self:: $loader) {return self:: $loader;} spl_autoload_register ( Array (' Composerautoloaderinit73612b48e6c3d0de8d56e03dece61d11 ', ' Loadclassloader '), true, true); Self:: $loader = $loader = new \composer\autoload\classloader (); Spl_autoload_unregister (Array (' Composerautoloaderinit73612b48e6c3d0de8d56e03dece61d11 ', ' LoadClassLoader ')); $vendorDir = DirName (__dir__); Verdor third-party class library provider Directory $baseDir = dirname ($vendorDir); The entire app's directory $includePaths = Require __dir__. '/include_paths.php '; Array_push ($includePaths, Get_include_path ()); Set_include_path (Join (Path_separator, $includePaths)); $map = Require __dir__. '/autoload_namespaces.php '; foreach ($map as $namespacE = $path) {$loader->set ($namespace, $path);} $map = Require __dir__. '/autoload_psr4.php '; foreach ($map as $namespace = + $path) {$loader->setpsr4 ($namespace, $path);} $classMap = Require __dir__. '/autoload_classmap.php '; if ($classMap) {$loader->addclassmap ($CLASSMAP);} $loader->register (true); $includeFiles = Require __dir__. '/autoload_files.php ';  foreach ($includeFiles as $file) {composerrequire73612b48e6c3d0de8d56e03dece61d11 ($file);} return $loader; }}function Composerrequire73612b48e6c3d0de8d56e03dece61d11 ($file) {require $file;}

The

Initializes the ClassLoader class first, then registers/loads directly with the 4 loading methods mentioned above, and some core code for ClassLoader is as follows:

/** * @param array $classMap Class to filename map */Public Function Addclassmap (array $classMap) {if ($this->clas  SMAP) {$this->classmap = Array_merge ($this->classmap, $CLASSMAP);  } else {$this->classmap = $classMap; }}/** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix  . * * @param string $prefix the prefix * @param array|string $paths the PSR-0 base directories */Public function set ($p  Refix, $paths) {if (! $prefix) {$this->fallbackdirspsr0 = (array) $paths;  } else {$this->prefixespsr0[$prefix [0]][$prefix] = (array) $paths; }}/** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this Nam  Espace. * * @param string $prefix The Prefix/namespace, with trailing ' \ \ ' * @param array|string $paths the PSR-4 base director IES * * @throws \invalidargumentexception */Public Function SETPSR4 ($prefix, $paths) {if (! $prefix) {$this-&GT;FALLBACKDIRSPSR4 = (array) $paths;   } else {$length = strlen ($prefix); if (' \ \ '!== $prefix [$length-1]) {throw new \invalidargumentexception ("A non-empty PSR-4 prefix must end with A name   Space separator. ");   $this->prefixlengthspsr4[$prefix [0]][$prefix] = $length;  $this->prefixdirspsr4[$prefix] = (array) $paths;  }}/** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not */Public function register ($prepend = false) {Spl_a Utoload_register (Array ($this, ' LoadClass '), true, $prepend);  }/** * Loads the given class or interface. * * @param string $class The name of the class * @return Bool|null True if loaded, NULL otherwise */Public function lo   Adclass ($class) {if ($file = $this->findfile ($class)) {includefile ($file);  return true;  }}/** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return String|falSe the path if found, false otherwise */Public function FindFile ($class) {//This is a bug for php5.3.0-5.3.2 see https://bugs.ph  p.net/50731 if (' \ \ ' = = $class [0]) {$class = substr ($class, 1);  }//class map method lookup if (isset ($this->classmap[$class]) {return $this->classmap[$class];  }//PSR-0/4 Method Lookup $file = $this->findfilewithextension ($class, '. php '); Search for Hack files If we is running on HHVM if ($file = = = NULL && defined (' hhvm_version ')) {$file = $th  Is->findfilewithextension ($class, '. hh ');   if ($file = = = null) {//Remember that this class does not exist.  return $this->classmap[$class] = false; } return $file; } Private Function Findfilewithextension ($class, $ext) {//PSR-4 lookup $LOGICALPATHPSR 4 = STRTR ($class, ' \ \ ', DIRECTOR Y_separator).  $ext;  $first = $class [0]; if (Isset ($this->prefixlengthspsr4[$first])) {foreach ($this->prefixlengthspsr4[$first] as $prefix = = $ Length) {if (0 = = Strpos ($class, $prefix)){foreach ($this->prefixdirspsr4[$prefix] as $dir) {if (file_exists ($file = $dir. Directory_separator.      SUBSTR ($LOGICALPATHPSR 4, $length)) {return $file;  }}}}}//PSR-4 fallback dirs foreach ($this->fallbackdirspsr4 as $dir) {if (file_exists ($file = $dir . Directory_separator.   $LOGICALPATHPSR 4)) {return $file; }}//PSR-0 lookup if (false!== $pos = Strrpos ($class, ' \ \ ')) {//namespaced class name $LOGICALPATHPSR 0 = subst R ($LOGICALPATHPSR 4, 0, $pos + 1).  STRTR (substr ($LOGICALPATHPSR 4, $pos + 1), ' _ ', directory_separator);  } else {//Pear-like class name $LOGICALPATHPSR 0 = strtr ($class, ' _ ', directory_separator). $ext; } if (Isset ($this->prefixespsr0[$first]) {foreach ($this->prefixespsr0[$first] as $prefix + = $dirs) {if (0 = = Strpos ($class, $prefix)) {foreach ($dirs as $dir) {if (file_exists ($file = $dir). Directory_separator.      $LOGICALPATHPSR 0)) {return $file; }     }    }}}//PSR-0 fallback dirs foreach ($this->fallbackdirspsr0 as $dir) {if (file_exists ($file = $dir. Directory_separator.   $LOGICALPATHPSR 0)) {return $file;  }}//PSR-0 include paths.  if ($this->useincludepath && $file = Stream_resolve_include_path ($LOGICALPATHPSR 0)) {return $file; }}/** * Scope isolated include. * * Prevents access to $this/self from included files. */function Includefile ($file) {include $file;}


Why does PHP auto-load equate to a bunch of require above?

Liang was right. With AutoLoad
Usage is fairly simple, the only condition your class name must be symmetric with the directory name.
can see examples
If log.php is in the class directory, the class name should be taken as follows: Class_log
Class Class_log {}
?>

After that, add this function to the area where you want to include it.
can see examples

function __autoload ($class) {
$path _array = Explode (' _ ', $class); Separate class and log into arrays

$path = Implode (Directory_separator, $path _array); Connect the array with/reconnect

Include $path. '. PHP '; The final direct include is OK.

}

$log = new Class_log ();
?>

It should work according to this method.

PHP Auto-Load Object __autoload

It's not like that!
The __autoload function automatically calls __autoload when new ClassName is present and there is no class ClassName, and the function has a parameter that is the class name and then defines the execution code of the lookup class in this function and includes it.
Reference: Www.oscodes.net

http://www.bkjia.com/PHPjc/865616.html www.bkjia.com true http://www.bkjia.com/PHPjc/865616.html techarticle PHP Management Dependency (dependency) Relationship tool composer automatic loading (autoload), dependencyautoload For example, suppose our project wants to use monolog this log tool, it needs ...

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