侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP管理依赖(dependency)关系工具 Composer的自动加载(autoload)

php  /  管理员 发布于 7年前   403

举例来说,假设我们的项目想要使用 monolog 这个日志工具,就需要在composer.json里告诉composer我们需要它:

{ "require": {  "monolog/monolog": "1.*" }}

之后执行:

php composer.phar install

好,现在安装完了,该怎么使用呢?Composer自动生成了一个autoload文件,你只需要引用它

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

然后就可以非常方便的去使用第三方的类库了,是不是感觉很棒啊!对于我们需要的monolog,就可以这样用了:

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

在这个过程中,Composer做了什么呢?它生成了一个autoloader,再根据各个包自己的autoload配置,从而帮我们进行自动加载的工作。(如果对autoload这部分内容不太了解,可以看我之前的 一篇文章
)接下来让我们看看Composer是怎么做的吧。

对于第三方包的自动加载,Composer提供了四种方式的支持,分别是 PSR-0和PSR-4的自动加载(我的一篇文章也有介绍过它们),生成class-map,和直接包含files的方式。

PSR-4是composer推荐使用的一种方式,因为它更易使用并能带来更简洁的目录结构。在composer.json里是这样进行配置的:

{  "autoload": {    "psr-4": {      "Foo\\": "src/",    }  }}

key和value就定义出了namespace以及到相应path的映射。按照PSR-4的规则,当试图自动加载 "Foo\\Bar\\Baz" 这个class时,会去寻找 "src/Bar/Baz.php" 这个文件,如果它存在则进行加载。注意, "Foo\\"
并没有出现在文件路径中,这是与PSR-0不同的一点,如果PSR-0有此配置,那么会去寻找

"src/Foo/Bar/Baz.php"

这个文件。

另外注意PSR-4和PSR-0的配置里,"Foo\\"结尾的命名空间分隔符必须加上并且进行转义,以防出现"Foo"匹配到了"FooBar"这样的意外发生。

在composer安装或更新完之后,psr-4的配置换被转换成namespace为key,dir path为value的Map的形式,并写入生成的 vendor/composer/autoload_psr4.php 文件之中。

{  "autoload": {    "psr-0": {      "Foo\\": "src/",    }  }}

最终这个配置也以Map的形式写入生成的

vendor/composer/autoload_namespaces.php

文件之中。

Class-map方式,则是通过配置指定的目录或文件,然后在Composer安装或更新时,它会扫描指定目录下以.php或.inc结尾的文件中的class,生成class到指定file path的映射,并加入新生成的 vendor/composer/autoload_classmap.php 文件中,。

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

例如src/下有一个BaseController类,那么在autoload_classmap.php文件中,就会生成这样的配置:

'BaseController' => $baseDir . '/src/BaseController.php'

Files方式,就是手动指定供直接加载的文件。比如说我们有一系列全局的helper functions,可以放到一个helper文件里然后直接进行加载

{  "autoload": {    "files": ["src/MyLibrary/functions.php"]  }}

它会生成一个array,包含这些配置中指定的files,再写入新生成的

vendor/composer/autoload_files.php

文件中,以供autoloader直接进行加载。

下面来看看composer autoload的代码吧

 $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;}

首先初始化ClassLoader类,然后依次用上面提到的4种加载方式来注册/直接加载,ClassLoader的一些核心代码如下:

/**  * @param array $classMap Class to filename map  */ public function addClassMap(array $classMap) {  if ($this->classMap) {   $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($prefix, $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 namespace.  *  * @param string  $prefix The prefix/namespace, with trailing '\\'  * @param array|string $paths The PSR-4 base directories  *  * @throws \InvalidArgumentException  */ public function setPsr4($prefix, $paths) {  if (!$prefix) {   $this->fallbackDirsPsr4 = (array) $paths;  } else {   $length = strlen($prefix);   if ('\\' !== $prefix[$length - 1]) {    throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace 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_autoload_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 loadClass($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) {  //这是PHP5.3.0 - 5.3.2的一个bug 详见https://bugs.php.net/50731  if ('\\' == $class[0]) {   $class = substr($class, 1);  }  // class map 方式的查找  if (isset($this->classMap[$class])) {   return $this->classMap[$class];  }  //psr-0/4方式的查找  $file = $this->findFileWithExtension($class, '.php');  // Search for Hack files if we are running on HHVM  if ($file === null && defined('HHVM_VERSION')) {   $file = $this->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  $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_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($logicalPathPsr4, $length))) {       return $file;      }     }    }   }  }  // PSR-4 fallback dirs  foreach ($this->fallbackDirsPsr4 as $dir) {   if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {    return $file;   }  }  // PSR-0 lookup  if (false !== $pos = strrpos($class, '\\')) {   // namespaced class name   $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)    . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);  } else {   // PEAR-like class name   $logicalPathPsr0 = 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 . $logicalPathPsr0)) {       return $file;      }     }    }   }  }  // PSR-0 fallback dirs  foreach ($this->fallbackDirsPsr0 as $dir) {   if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {    return $file;   }  }  // PSR-0 include paths.  if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {   return $file;  } }/** * Scope isolated include. * * Prevents access to $this/self from included files. */function includeFile($file){ include $file;}

您可能感兴趣的文章:

  • 说说PHP的autoLoad自动加载机制
  • php自动加载的两种实现方法
  • PHP命名空间和自动加载类
  • PHP的autoload自动加载机制使用说明
  • php自动加载方式集合
  • PHP spl_autoload_register实现自动加载研究
  • PHP动态地创建属性和方法, 对象的复制, 对象的比较,加载指定的文件,自动加载类文件,命名空间
  • PHP中类的自动加载的方法
  • PHP autoload与spl_autoload自动加载机制的深入理解
  • PHP 自动加载的简单实现(推荐)
  • PHP中的自动加载操作实现方法详解


  • 上一条:
    PHPer 需要了解的 5 个 Composer 小技巧
    下一条:
    PHP实现取得HTTP请求的原文
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客