# 对composer自动加载的认识

**URL:** <https://www.shiqidu.com/t/topic/369>\
**Category:** 开发调优\
**Tags:** PHP\
**Created:** [2018 年2 月 5 日 07:21 UTC](https://www.shiqidu.com/t/topic/369 "2018-02-05T07:21:49Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![dajiang](https://www.shiqidu.com/user_avatar/www.shiqidu.com/dajiang/32/468_2.png) [@dajiang](https://www.shiqidu.com/u/dajiang)\
发布日期： [2018 年2 月 5 日 07:21 UTC](https://www.shiqidu.com/t/topic/369/1 "2018-02-05T07:21:49Z")

</div>

通过composer下载的第三方扩展，会自动有一个vendor目录和一个autoload.php，vendor目录中包含composer目录,目录结构如下

![0a9b337cb2141932049f455503dbf32a.png](https://discourse.shiqidu.com/uploads_nj/article/20180205/0a9b337cb2141932049f455503dbf32a.png)

在使用过程中首先应该在如自动加载脚本

```php
//autoloaderwhenusingComposer
require('D:/www/xhl/phpbarcode/vendor/autoload.php');
//autoload.php脚本中会自动载入autoload_real.php,在其中载入composer\autoload_static.php;
//在autoload_static.php中
publicstaticfunctiongetInitializer(ClassLoader$loader)
{
return\Closure::bind(function()use($loader){
$loader->prefixLengthsPsr4=ComposerStaticInit713d85be4d0a0ba294ebd5a1837c9432::$prefixLengthsPsr4;
$loader->prefixDirsPsr4=ComposerStaticInit713d85be4d0a0ba294ebd5a1837c9432::$prefixDirsPsr4;

},null,ClassLoader::class);
}

```

通过闭包函数为$loader即composer\ClassLoader.php对象赋予属性并注册成自动加载函数

```php
spl_autoload_register(array($this,'loadClass'),true,$prepend);

```

大部分通过findFileWithExtension找到对应的自动加载类；

```php
$this->prefixLengths

```

Psr4提供了一个快速查找的分组对应的命名空间

```php
$prefixLengths

```

Psr4中的长度决定截取的类名，其中的索引值大小写敏感

```php
$length=$this->prefixLengthsPsr4[$first][$search];
if(file_exists($file=$dir.DIRECTORY_SEPARATOR.substr($logicalPathPsr4,$length))){
return$file;
}

```
