


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!

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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