


Detailed explanation of the implementation of composer automatic loading in the Laravel framework
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 文件。
总结
您可能感兴趣的文章:
The above is the detailed content of Detailed explanation of the implementation of composer automatic loading in the Laravel framework. For more information, please follow other related articles on the PHP Chinese website!

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

I'm having a tricky problem when doing a mail marketing campaign: how to efficiently create and send mail in HTML format. The traditional approach is to write code manually and send emails using an SMTP server, but this is not only time consuming, but also error-prone. After trying multiple solutions, I discovered DUWA.io, a simple and easy-to-use RESTAPI that helps me create and send HTML mail quickly. To further simplify the development process, I decided to use Composer to install and manage DUWA.io's PHP library - captaindoe/duwa.

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

I had a tough problem when working on a project with a large number of Doctrine entities: Every time the entity is serialized and deserialized, the performance becomes very inefficient, resulting in a significant increase in system response time. I've tried multiple optimization methods, but it doesn't work well. Fortunately, by using sidus/doctrine-serializer-bundle, I successfully solved this problem, significantly improving the performance of the project.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.
