


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











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 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.

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

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

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.

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.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.
