简介
一般在框架中都会用到 composer 工具 , 用它来管理依赖。其中 composer 有类的自动加载机制,可以加载 composer 下载的库中的所有的类文件。那么 composer 的自动加载机制是怎么实现的呢?
composer 自动加载原理
以在 Laravel 框架中为例:
1. 首先在入口文件(/public/index.php)中引入了 autoload.php
```
require __DIR__.'/../vendor/autoload.php';
```
2. 我们看看 autoload.php 的内容
```
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit1215780529014c2b50a6fca7ce889273::getLoader();
```
3. 我们再看看 autoload_real.php 的内容
```
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit1215780529014c2b50a6fca7ce889273
{
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('ComposerAutoloaderInit1215780529014c2b50a6fca7ce889273', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit1215780529014c2b50a6fca7ce889273', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit1215780529014c2b50a6fca7ce889273::getInitializer($loader));
} else {
$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);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit1215780529014c2b50a6fca7ce889273::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire1215780529014c2b50a6fca7ce889273($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire1215780529014c2b50a6fca7ce889273($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
```
可以看出这一段是 composer 自动加载的重点,首先在 autoload.php 中调用
ComposerAutoloaderInit1215780529014c2b50a6fca7ce889273::getLoader () 方法,getLoader () 首先判断当前