本人水平有限,如有錯(cuò)誤望告知,謝謝!
Laravel如何實(shí)現(xiàn)自動(dòng)加載類
Laravel使用的是composer的自動(dòng)加載。
首先看 vendor/autoload.php文件
1
2
3
4
|
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer/autoload_real.php' ; return ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3::getLoader(); |
代碼很少,查看__DIR__ . '/composer/autoload_real.php'文件。 有一個(gè)類ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3,該類的名字比較奇特,主要為了防止重名。回到上面的代碼,可以看到調(diào)用了getLoader()方法;
看一下部分代碼
1
2
3
4
5
6
7
|
if (null !== self:: $loader ) { return self:: $loader ; } spl_autoload_register( array ( 'ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3' , 'loadClassLoader' ), true, true); self:: $loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister( array ( 'ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3' , 'loadClassLoader' )); |
這里自動(dòng)加載了當(dāng)前類的loadClassLoader靜態(tài)方法,該方法加載了__DIR__ . '/ClassLoader.php'文件,該文件中的類起到了整個(gè)框架類自動(dòng)加載的作用。
回到autoload_real.php文件的getLoader()方法,看剩下部分代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
$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\ComposerStaticInit5586036d8fdd45ae351f9a5ae924a5a3::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 ); } } |
這里主要加載一些自動(dòng)加載類相關(guān)的資源。
隨后調(diào)用$loader->register(true);
這個(gè)方法比較重要
1
2
3
4
|
public function register( $prepend = false) { spl_autoload_register( array ( $this , 'loadClass' ), true, $prepend ); } |
注冊了loadClass方法,并且是放在隊(duì)列的head。
查看loadClass方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/** * Loads the given class or interface. * * @param string $class The name of the class * @return bool|null True if loaded, null otherwise */ public function loadClass( $class ) { if ( $file = $this ->findFile( $class )) { includeFile( $file ); return true; } } |
當(dāng)實(shí)例化類的時(shí)候,找不到類,就自動(dòng)會調(diào)用該方法,該方法加載了需要的類,這個(gè)方法十分重要。
現(xiàn)在看一下$this->findFile($class)方法內(nèi)使用了之前getLoader()方法加載的相關(guān)資源。
現(xiàn)在整個(gè)Laravel框架如何自動(dòng)加載類已經(jīng)很明顯了。每當(dāng)實(shí)例化類的時(shí)候,會自動(dòng)調(diào)用 ClassLoader的loadClass方法,加載需要的類。
以上這篇Laravel如何實(shí)現(xiàn)自動(dòng)加載類就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/sweatOtt/article/details/55001209