新手必了解的Composer 实现自动加载原理
下面由composer教程栏目给大家介绍新手必了解的Composer 实现自动加载原理,希望对需要的朋友有所帮助!
简介
一般在框架中都会用到 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 () 首先判断当前loader是不是null,如果不为null就直接返回,否则就初始化一个calssloader类给赋值给 loader 是不是 null,如果不为 null 就直接返回,否则就初始化一个 ClassLoader 类给赋值给 loader,接着将 autoload_namespaces.php、autoload_psr4.php、autoload_classmap.php 文件中的内容加入到 $loader 中对应的数组中,然后给注册 loadClass 函数,将 autoload_files.php 中的所有路径所示的文件都包含进来,当在 new 一个类的时候如果没有找到相关的类就会触发这个 loadClass 函数,在 loadClass () 又调用了 findFile () 去查找相应的文件,找到相应文件后就会返回该文件,然后 loadClass 调用 includeFile () 方法将该文件 include 进去,否则 findFile 返回 false,这样就完成了自动加载
4. 下面来看一下 findFile ()
public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath.'\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { 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; } return false; }
4. findFile () 函数先在 classMap 中查找,如果找不到的话就会尝试在 apcu 缓存中查找,如果还是找不到的话就会调用 findFileWithExtension () 函数查找,如果找到了就会将该文件加到 apcu 缓存,如果找不到的话就会在 missingClasses 数组中设一个标记表示识这个类找不到
findFileWithExtension()方法根据之前通过 −> (loader−>set(namespace, ℎ)和path)和loader->setPsr4( ,namespace,path)方法设置的信息找出类文件的路径信息
5. 在上面有的地方用到了 spl_autoload_register 和 spl_autoload_unregister 函数
1. spl_autoload_register 函数
1.spl_autoload_register — 注册给定的函数作为 __autoload 的实现,
bool spl_autoload_register ([ callable [, autoloadfunction[,boolthrow = true [, bool $prepend = false ]]] )
2.prepend
如果是 true,spl_autoload_register () 会添加函数到队列之首,而不是队列尾部。
3.如果在你的程序中已经实现了 autoload () 函数,它必须显式注册到 autoload () 队列中。因为 spl_autoload_register () 函数会将 Zend Engine 中的__autoload () 函数取代为 spl_autoload () 或 spl_autoload_call ()
例:
function __autoload($name) { require 'class/'.$name.'.php'; echo '1'; } function autoload_test($name) { echo '2'; } spl_autoload_register('autoload_test'); spl_autoload_register('__autoload'); $ca=new Ca();
2. spl_autoload_unregister 函数
spl_autoload_unregister — 注销已注册的 autoload () 函数,如果该函数队列处于激活状态,并且在给定函数注销后该队列变为空,则该函数队列将会变为无效。如果该函数注销后使得自动装载函数队列无效,即使存在有 autoload 函数它也不会自动激活。
bool spl_autoload_unregister ( mixed $autoload_function )
以上是新手必了解的Composer 实现自动加载原理的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Composer提供高级功能,包括:1.别名:定义包便捷名称以便重复引用;2.脚本:安装/更新包时执行自定义命令,用于创建数据库表或编译资源;3.冲突解决:使用优先级规则、满足性约束和包别名解决多个包对同个依赖版本的不同需求,以避免安装冲突。

答案:PHP微服务采用HelmCharts部署进行敏捷开发,并使用DockerContainer容器化以实现隔离和可扩展性。详细描述:使用HelmCharts自动部署PHP微服务,实现敏捷开发。Docker镜像允许对微服务进行快速迭代和版本控制。DockerContainer标准隔离微服务,而Kubernetes负责管理容器的可用性和可扩展性。利用Prometheus和Grafana监控微服务性能和健康状况,并创建告警和自动修复机制。

PHP数组转对象的方法:使用stdClass类使用json_decode()函数使用第三方库(如ArrayObject类、Hydrator库)

PHP代码版本控制:PHP开发中常用的版本控制系统(VCS)有两个:Git:分布式VCS,开发人员本地存储代码库副本,便于协作和离线工作。Subversion:集中式VCS,代码库唯一副本存储在中央服务器上,提供更多控制。VCS帮助团队跟踪更改、协作并回滚到早期版本。

使用Redis缓存可以大幅优化PHP数组分页的性能。可通过以下步骤实现:安装Redis客户端。连接到Redis服务器。创建缓存数据,将每页数据存储到Redis哈希中,密钥为"page:{page_number}"。从缓存中获取数据,避免对大型数组进行昂贵的操作。

答案:利用PHPCI/CD实现快速迭代,包括设置CI/CD管道、自动化测试和部署流程。设置CI/CD管道:选择CI/CD工具,配置代码存储库,定义构建管道。自动化测试:编写单元和集成测试,使用测试框架简化测试。实战案例:使用TravisCI:安装TravisCI,定义管道,启用管道,查看结果。实现持续交付:选择部署工具,定义部署管道,自动化部署。收益:提高开发效率、减少错误、缩短交付时间。

PHP数据结构可视化有三种主要技术:Graphviz:开源工具,可创建图表、有向无环图和决策树等图形表示。D3.js:JavaScript库,用于创建交互式、数据驱动的可视化,从PHP生成HTML和数据,再用D3.js在客户端可视化。ASCIIFlow:用于创建文本表示数据流图的库,适合流程和算法的可视化。

为了维护和更新PHPWeb服务和API,必须实施以下实践:更新依赖项以确保最新安全补丁。通过版本控制跟踪代码库更改和协作开发。自动化测试以验证更新不会影响功能。持续集成通过自动化流程确保代码验证。日志记录和监视有助于识别和解决问题。始终更新安全补丁以避免漏洞。
