laravel知识点: 加载器
参考: https://segmentfault.com/a/11...
参考: https://segmentfault.com/a/11...
使用加载器的目的
现在基本上所有的框架都使用composer来安装第三方包,并使用它的loader来加载类文件
要想使用某个类,或某个函数,必须要先导入定义该类或该函数的文件,使用自动加载器就不用手动加载,会自动加载相应的文件
如何配置composer.json看的自动加载
"autoload": {
"psr-4": {
"Barryvdh\\Debugbar\\": "src/", //值中最后的/可以省略,但键中最后的\不能省略
"HieuLe\\Active\\": "src/",
"HieuLe\\ActiveTest\\": "tests/",
"Wang\\": "./src/"
},
"psr-0": {
"DoctrineTest\\InstantiatorPerformance\\": "tests",
"DoctrineTest\\InstantiatorTest\\": "tests",
"DoctrineTest\\InstantiatorTestAsset\\": "tests",
"JakubOnderka\\PhpConsoleHighlighter": "src/",
"Mockery": "library/",
"Zhang\\": "./src/"
},
"files": [
"src/helpers.php","src/carbon_compat.php",
"src/Illuminate/Foundation/helpers.php",
"src/Illuminate/Support/helpers.php"
],
"classmap": ["hamcrest"],
},
// psr-0和psr-4对应的文件名不一样,psr-0的路径更深
// 官方推荐使用psr-4,慢慢淘汰psr-0
// psr-4必须以\结尾,psr-0没关系
// psr-0将类名中的_转为\,psr-4不转
use Wang\testClass, 那就对应src/testClass.php
use Wang\test\testClass, 那就对应src/test/testClass.php
use Zhang\testClass, 那就对应src/Zhang/testClass.php
use Zhang\test\testClass, 那就对应src/Zhang/test/testClass.php
// 对于不符合PSR规范的类,使用classmap来
了解加载器的几个属性
Composer\Autoload\ClassLoader Object(
// 与psr-4相关的3个属性
prefixLengthsPsr4 => [
//先小写字母倒序,后大写字母倒序,键名以\结尾,值为键名的长度
p => [
phpDocumentor\Reflection\ => 25
]
S =>[
Symfony\Polyfill\Mbstring\ => 26
Symfony\Component\VarDumper\ => 28
]
A => [
App\ => 4
]
]
prefixDirsPsr4 => [
phpDocumentor\Reflection\ => [
0 => 项目根目录/vendor/composer/../phpdocumentor/reflection-common/src
1 => 项目根目录/vendor/composer/../phpdocumentor/reflection-docblock/src
2 => 项目根目录/vendor/composer/../phpdocumentor/type-resolver/src
]
Symfony\Polyfill\Mbstring\ => [
[0] => 项目根目录/vendor/composer/../symfony/polyfill-mbstring
]
Symfony\Component\VarDumper\ => [
0 => 项目根目录/vendor/composer/../symfony/var-dumper
]
Symfony\Component\Translation\ => [
0 => 项目根目录/vendor/composer/../symfony/translation
]
App\ =>[
0 => 项目根目录/vendor/composer/../../app
]
]
fallbackDirsPsr4 => []
prefixesPsr0 => [
P => [
Prophecy\ => [
0 => 项目根目录/vendor/composer/../phpspec/prophecy/src
]
Parsedown => [
0 => 项目根目录/vendor/composer/../erusev/parsedown
]
]
D => [
Doctrine\Common\Lexer\ => [
0 => 项目根目录/vendor/composer/../doctrine/lexer/lib
]
]
]
fallbackDirsPsr0 => []
classMap => [
App\Console\Commands\CalculateActiveUser => 项目根目录/vendor/composer/../../app/Console/Commands/CalculateActiveUser.php
// 根据类名映射,导入相应文件
// 省略4300个,这里比较多
// "autoload": {
// "classmap": ["src/", "lib/", "Something.php"]
// }
phpDocumentor\Reflection\Types\Void_ => 项目根目录/vendor/composer/../phpdocumentor/type-resolver/src/Types/Void_.php
]
classMapAuthoritative =>
useIncludePath =>
missingClasses => [],
apcuPrefix =>
)
使用静态加载器
针对php版本大于5.06,没有安装HHVM虚拟机,并且没有将代码加密的情况,使用静态加载器
除了ClassLoader.php
,其余文件是自动生成的,它是根据package.json文件,当执行命令compser dumpautoload,就会生成这些文件,当使用静态加载器时,会读取autoload_static.php中相应的值