您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Laravel實(shí)現(xiàn)自動加載類的方法,小編覺得挺實(shí)用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
Laravel如何實(shí)現(xiàn)自動加載類
Laravel使用的是composer的自動加載。
首先看 vendor/autoload.php文件
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3::getLoader();
代碼很少,查看__DIR__ . '/composer/autoload_real.php'文件。 有一個類ComposerAutoloaderInit5586036d8fdd45ae351f9a5ae924a5a3,該類的名字比較奇特,主要為了防止重名?;氐缴厦娴拇a,可以看到調(diào)用了getLoader()方法;
看一下部分代碼
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)前類的loadClassLoader靜態(tài)方法,該方法加載了__DIR__ . '/ClassLoader.php'文件,該文件中的類起到了整個框架類自動加載的作用。
回到autoload_real.php文件的getLoader()方法,看剩下部分代碼
$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); } }
這里主要加載一些自動加載類相關(guān)的資源。
隨后調(diào)用$loader->register(true);
這個方法比較重要
public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); }
注冊了loadClass方法,并且是放在隊(duì)列的head。
查看loadClass方法
/** * 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í)例化類的時候,找不到類,就自動會調(diào)用該方法,該方法加載了需要的類,這個方法十分重要。
現(xiàn)在看一下$this->findFile($class)方法內(nèi)使用了之前getLoader()方法加載的相關(guān)資源。
現(xiàn)在整個Laravel框架如何自動加載類已經(jīng)很明顯了。每當(dāng)實(shí)例化類的時候,會自動調(diào)用 ClassLoader的loadClass方法,加載需要的類。
關(guān)于“Laravel實(shí)現(xiàn)自動加載類的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。