


How to implement automatic loading of composer in Laravel framework
这篇文章主要介绍了关于如何实现Laravel框架中composer自动加载,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
Laravel作为在国内国外都颇为流行的PHP框架,风格优雅,其拥有自己的一些特点。下面这篇文章主要给大家介绍了关于Laravel框架中composer自动加载实现的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。
基础
自动加载允许你通过即用即加载的方式来加载需要的类文件,而不用每次都写繁琐的require 和include语句。因此,每一次请求的执行过程都只加载必须的类,也不不要关心类的加载问题,只要需要的时候直接使用即可。
laravel 框架是通过composer 实现的自动加载。
是通过 下面的代码实现的。
require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit7b20e4d61e2f88170fbbc44c70d38a1f::getLoader();
首先我们对spl_autoload_register和spl_autoload_unregister 这两个函数进行解释一下。
spl_autoload_register 自动注册 一个或多个 自动加载函数,这些函数一般在 实例化类的时候,自动运行。
spl_autoload_unregister 恰恰相反。
贴上我实验的代码:
这是autoload.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2017/12/7 * Time: 14:10 */ namespace app; class Autoload { public function __construct() { $this->autoload(); } public function autoload(){ // spl_autoload_register(array('Autoload','ss'),true); 会触发致命错误,必须带上命名空间 spl_autoload_register(array('app\Autoload','ss'),true); } public function ss(){ echo 666; exit; } }
这是index.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2017/12/7 * Time: 14:10 */ require 'autoload.php'; $autoload=new \app\Autoload(); $b=new B();// 此时自动运行自动加载函数 echo 77; exit;
找到getLoader 这个函数,并对其进行分析:
public static function getLoader() { if (null !== self::$loader) { return self::$loader; } //注册自动加载函数,在加载或实例化类,运行loadClassLoader函数 spl_autoload_register(array('ComposerAutoloaderInit7b20e4d61e2f88170fbbc44c70d38a1f', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit7b20e4d61e2f88170fbbc44c70d38a1f', 'loadClassLoader')); /********************1******************************************************** $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); } /********************1******************************************************** $loader->register(true); $includeFiles = require __DIR__ . '/autoload_files.php'; foreach ($includeFiles as $fileIdentifier => $file) { composerRequire7b20e4d61e2f88170fbbc44c70d38a1f($fileIdentifier, $file); } return $loader; }}
/***** 包围的部分,主要对ClassLoader 中的
$prefixesPsr0 、$prefixDirsPsr4 、$classMap 等属性进行赋值。即加载一些配置好的文件,在后面进行加载或寻找文件时候,就是从加载的配置文件中寻找。寻找要加载的类主要通过register 函数来实现。然后分析register函数。
public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); }
发现实际将该类中loadClass 函数注册为自动加载函数。于是开始分析loadClass函数,最终是通过findFile进行类的寻找。
public function findFile($class) { /// 特别注意 参数$class 是根据命名空间生成的class名称,具体请参考命名空间特性。 // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 if ('\\' == $class[0]) { $class = substr($class, 1); } // class map lookup 首先从加载的classMap 中寻找 if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative) { return false; } // 从刚才加载的配置文件中寻找文件。先按照 psr4 规则寻找,再按照psr0 寻找 // 两种规则的不同主要是对下划线的处理方式。 $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; }
至此register函数分析完。我们接着分析getLoader函数剩余代码。
$includeFiles = require __DIR__ . '/autoload_files.php'; foreach ($includeFiles as $fileIdentifier => $file) { composerRequire7b20e4d61e2f88170fbbc44c70d38a1f($fileIdentifier, $file); }
这段代码其实就是加载autoload_file.php 文件。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of How to implement automatic loading of composer in Laravel framework. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
