国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home PHP Framework Laravel Code analysis of Autoloader module in Laravel framework

Code analysis of Autoloader module in Laravel framework

Jul 31, 2018 pm 03:57 PM

本篇文章給大家分享的內(nèi)容是關(guān)于Laravel框架中Autoloader模塊的代碼分析,有一定的參考價(jià)值,希望可以幫助到有需要的朋友。

首先是中文注釋:

<?php namespace Laravel;

class Autoloader {

	/**
	 * 類名到文件名得映射
	 *
	 * @var array
	 */
	public static $mappings = array();

	/**
     * PSR-0命名轉(zhuǎn)換目錄
	 *
	 * @var array
	 */
	public static $directories = array();

	/**
	 * 命名空間和目錄的映射
	 *
	 * @var array
	 */
	public static $namespaces = array();

	/**
	 * 下劃線類庫(kù)和目錄映射
	 *
	 * @var array
	 */
	public static $underscored = array();

	/**
	 * 自動(dòng)加載類的別名
	 *
	 * @var array
	 */
	public static $aliases = array();

	/**
	 * Load the file corresponding to a given class.
	 *
	 * This method is registered in the bootstrap file as an SPL auto-loader.
	 *
	 * @param  string  $class
	 * @return void
	 */
	public static function load($class)
	{
		// 嘗試類是否有別名
		if (isset(static::$aliases[$class]))
		{
			return class_alias(static::$aliases[$class], $class);
		}

		// 查找映射
		elseif (isset(static::$mappings[$class]))
		{
			require static::$mappings[$class];

			return;
		}

		// 加載這個(gè)新的類
		foreach (static::$namespaces as $namespace => $directory)
		{
            # 支持函數(shù) 是否命名空間開頭 在helpers.php中
			if (starts_with($class, $namespace))
			{
				return static::load_namespaced($class, $namespace, $directory);
			}
		}

		static::load_psr($class);
	}

	/**
	 * 從給定的目錄加載命名空間
	 *
	 * @param  string  $class
	 * @param  string  $namespace
	 * @param  string  $directory
	 * @return void
	 */
	protected static function load_namespaced($class, $namespace, $directory)
	{
		return static::load_psr(substr($class, strlen($namespace)), $directory);
	}

	/**
	 * 使用PSR-0標(biāo)準(zhǔn)來(lái)試圖解析一個(gè)類
	 *
	 * @param  string  $class
	 * @param  string  $directory
	 * @return void
	 */
	protected static function load_psr($class, $directory = null)
	{
        // 用PSR-0來(lái)解析類 使之變成路徑字符串
		$file = str_replace(array(&#39;\\&#39;, &#39;_&#39;), &#39;/&#39;, $class);

		$directories = $directory ?: static::$directories; // 獲得類路徑

		$lower = strtolower($file); # 默認(rèn)全部小寫

		// 嘗試解析
		foreach ((array) $directories as $directory)
		{
			if (file_exists($path = $directory.$lower.EXT))
			{
				return require $path;
			}
			elseif (file_exists($path = $directory.$file.EXT))
			{
				return require $path;
			}
		}
	}

	/**
	 * 注冊(cè)一個(gè)數(shù)組 包含類路徑映射
	 *
	 * @param  array  $mappings
	 * @return void
	 */
	public static function map($mappings)
	{
		static::$mappings = array_merge(static::$mappings, $mappings);
	}

	/**
	 * 注冊(cè)類的別名
	 *
	 * @param  string  $class
	 * @param  string  $alias
	 * @return void
	 */
	public static function alias($class, $alias)
	{
		static::$aliases[$alias] = $class;
	}

	/**
	 * 注冊(cè)目錄
	 *
	 * @param  string|array  $directory
	 * @return void
	 */
	public static function directories($directory)
	{
		$directories = static::format($directory);

		static::$directories = array_unique(array_merge(static::$directories, $directories));
	}

	/**
	 * 映射命名空間和目錄
	 *
	 * @param  array   $mappings
	 * @param  string  $append
	 * @return void
	 */
	public static function namespaces($mappings, $append = &#39;\\&#39;)
	{
		$mappings = static::format_mappings($mappings, $append);

		static::$namespaces = array_merge($mappings, static::$namespaces); # 合并之后: (array "命名空間", array "命名空間","路徑")
	}

	/**
	 * 注冊(cè)下劃線命名空間
	 *
	 * @param  array  $mappings
	 * @return void
	 */
	public static function underscored($mappings)
	{
		static::namespaces($mappings, &#39;_&#39;); # 下劃線風(fēng)格
	}

	/**
	 * 格式目錄映射
	 *
	 * @param  array   $mappings
	 * @param  string  $append
	 * @return array
	 */
	protected static function format_mappings($mappings, $append)
	{
		foreach ($mappings as $namespace => $directory)
		{
			# 清理命名空間
			$namespace = trim($namespace, $append).$append;

			unset(static::$namespaces[$namespace]); # 去除之前的 如果存在的話

			$namespaces[$namespace] = head(static::format($directory)); # 一個(gè)命名空間只能對(duì)應(yīng)一個(gè)目錄
		}

		return $namespaces;
	}

	/**
	 * 格式化一個(gè)目錄數(shù)組
	 *
	 * @param  array  $directories
	 * @return array
	 */
	protected static function format($directories)
	{
		return array_map(function($directory)
		{
			return rtrim($directory, DS).DS;# 清理目錄
		
		}, (array) $directories); // 用map遍歷目錄數(shù)組
	}

}

改類被自動(dòng)裝在到spl中:

spl_autoload_register(array(&#39;Laravel\\Autoloader&#39;, &#39;load&#39;)); # spl_autoload_register array 命名空間,具體方法

注冊(cè)好之后,就載入一些預(yù)先設(shè)置好的配置:

定義系統(tǒng)root

Autoloader::namespaces(array(&#39;Laravel&#39; => path(&#39;sys&#39;))); # 定義Laravel系統(tǒng)根目錄映射

然后是默認(rèn)使用的ORM框架

# 定義EloquentORM框架
Autoloader::map(array(
	&#39;Laravel\\Database\\Eloquent\\Relationships\\Belongs_To&#39; 
                    => path(&#39;sys&#39;).&#39;database/eloquent/relationships/belongs_to&#39;.EXT,
	&#39;Laravel\\Database\\Eloquent\\Relationships\\Has_Many&#39; 
                    => path(&#39;sys&#39;).&#39;database/eloquent/relationships/has_many&#39;.EXT,
	&#39;Laravel\\Database\\Eloquent\\Relationships\\Has_Many_And_Belongs_To&#39; 
                    => path(&#39;sys&#39;).&#39;database/eloquent/relationships/has_many_and_belongs_to&#39;.EXT,
	&#39;Laravel\\Database\\Eloquent\\Relationships\\Has_One&#39; 
                    => path(&#39;sys&#39;).&#39;database/eloquent/relationships/has_one&#39;.EXT,
	&#39;Laravel\\Database\\Eloquent\\Relationships\\Has_One_Or_Many&#39; 
                    => path(&#39;sys&#39;).&#39;database/eloquent/relationships/has_one_or_many&#39;.EXT,
));

隨后是Symfony的HTTP組件和Console組件

# Symfony組件加載
Autoloader::namespaces(array(
	&#39;Symfony\Component\Console&#39; 
                    => path(&#39;sys&#39;).&#39;vendor/Symfony/Component/Console&#39;,
	&#39;Symfony\Component\HttpFoundation&#39;
                    => path(&#39;sys&#39;).&#39;vendor/Symfony/Component/HttpFoundation&#39;,
));

當(dāng)然,不要忘記了application.php中的配置

&#39;aliases&#39; => array(
		&#39;Auth&#39;       	=> &#39;Laravel\\Auth&#39;,
		&#39;Authenticator&#39; => &#39;Laravel\\Auth\\Drivers\\Driver&#39;,
		&#39;Asset&#39;      	=> &#39;Laravel\\Asset&#39;,
		&#39;Autoloader&#39; 	=> &#39;Laravel\\Autoloader&#39;,
		&#39;Blade&#39;      	=> &#39;Laravel\\Blade&#39;,
		&#39;Bundle&#39;     	=> &#39;Laravel\\Bundle&#39;,
		&#39;Cache&#39;      	=> &#39;Laravel\\Cache&#39;,
		&#39;Config&#39;     	=> &#39;Laravel\\Config&#39;,
		&#39;Controller&#39; 	=> &#39;Laravel\\Routing\\Controller&#39;,
		&#39;Cookie&#39;     	=> &#39;Laravel\\Cookie&#39;,
		&#39;Crypter&#39;    	=> &#39;Laravel\\Crypter&#39;,
		&#39;DB&#39;         	=> &#39;Laravel\\Database&#39;,
		&#39;Eloquent&#39;   	=> &#39;Laravel\\Database\\Eloquent\\Model&#39;,
		&#39;Event&#39;      	=> &#39;Laravel\\Event&#39;,
		&#39;File&#39;       	=> &#39;Laravel\\File&#39;,
		&#39;Filter&#39;     	=> &#39;Laravel\\Routing\\Filter&#39;,
		&#39;Form&#39;       	=> &#39;Laravel\\Form&#39;,
		&#39;Hash&#39;       	=> &#39;Laravel\\Hash&#39;,
		&#39;HTML&#39;       	=> &#39;Laravel\\HTML&#39;,
		&#39;Input&#39;      	=> &#39;Laravel\\Input&#39;,
		&#39;IoC&#39;        	=> &#39;Laravel\\IoC&#39;,
		&#39;Lang&#39;       	=> &#39;Laravel\\Lang&#39;,
		&#39;Log&#39;        	=> &#39;Laravel\\Log&#39;,
		&#39;Memcached&#39;  	=> &#39;Laravel\\Memcached&#39;,
		&#39;Paginator&#39;  	=> &#39;Laravel\\Paginator&#39;,
		&#39;Profiler&#39;  	=> &#39;Laravel\\Profiling\\Profiler&#39;,
		&#39;URL&#39;        	=> &#39;Laravel\\URL&#39;,
		&#39;Redirect&#39;   	=> &#39;Laravel\\Redirect&#39;,
		&#39;Redis&#39;      	=> &#39;Laravel\\Redis&#39;,
		&#39;Request&#39;    	=> &#39;Laravel\\Request&#39;,
		&#39;Response&#39;   	=> &#39;Laravel\\Response&#39;,
		&#39;Route&#39;      	=> &#39;Laravel\\Routing\\Route&#39;,
		&#39;Router&#39;     	=> &#39;Laravel\\Routing\\Router&#39;,
		&#39;Schema&#39;     	=> &#39;Laravel\\Database\\Schema&#39;,
		&#39;Section&#39;    	=> &#39;Laravel\\Section&#39;,
		&#39;Session&#39;    	=> &#39;Laravel\\Session&#39;,
		&#39;Str&#39;        	=> &#39;Laravel\\Str&#39;,
		&#39;Task&#39;       	=> &#39;Laravel\\CLI\\Tasks\\Task&#39;,
		&#39;URI&#39;        	=> &#39;Laravel\\URI&#39;,
		&#39;Validator&#39;  	=> &#39;Laravel\\Validator&#39;,
		&#39;View&#39;       	=> &#39;Laravel\\View&#39;,
	),

基本上流程就出來(lái)了。

牽扯的重要的文件地址:

laravel/core.php
laravel/autoloader.php
application/config/application.php

配合Ioc,夠用了。下次分析一下laravel的Ioc,不過(guò)個(gè)人感覺功能太少。使用仿spring的Ding更好

以上就是本篇文章的全部?jī)?nèi)容了,更多l(xiāng)aravel內(nèi)容請(qǐng)關(guān)注laravel框架入門教程

相關(guān)文章推薦:

實(shí)時(shí)聊天室:基于Laravel+Pusher+Vue通過(guò)事件廣播實(shí)現(xiàn)

laravel框架中TokenMismatchException的異常處理內(nèi)容

Laravel框架中外觀模式的深入解析

相關(guān)課程推薦:

2017年最新的五個(gè)Laravel視頻教程推薦

The above is the detailed content of Code analysis of Autoloader module in Laravel framework. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are policies in Laravel, and how are they used? What are policies in Laravel, and how are they used? Jun 21, 2025 am 12:21 AM

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

How do I install Laravel on my operating system (Windows, macOS, Linux)? How do I install Laravel on my operating system (Windows, macOS, Linux)? Jun 19, 2025 am 12:31 AM

Yes,youcaninstallLaravelonanyoperatingsystembyfollowingthesesteps:1.InstallPHPandrequiredextensionslikembstring,openssl,andxmlusingtoolslikeXAMPPonWindows,HomebrewonmacOS,oraptonLinux;2.InstallComposer,usinganinstalleronWindowsorterminalcommandsonmac

What are controllers in Laravel, and what is their purpose? What are controllers in Laravel, and what is their purpose? Jun 20, 2025 am 12:31 AM

The main role of the controller in Laravel is to process HTTP requests and return responses to keep the code neat and maintainable. By concentrating the relevant request logic into a class, the controller makes the routing file simpler, such as putting user profile display, editing and deletion operations in different methods of UserController. The creation of a controller can be implemented through the Artisan command phpartisanmake:controllerUserController, while the resource controller is generated using the --resource option, covering methods for standard CRUD operations. Then you need to bind the controller in the route, such as Route::get('/user/{id

How do I customize the authentication views and logic in Laravel? How do I customize the authentication views and logic in Laravel? Jun 22, 2025 am 01:01 AM

Laravel allows custom authentication views and logic by overriding the default stub and controller. 1. To customize the authentication view, use the command phpartisanvendor:publish-tag=laravel-auth to copy the default Blade template to the resources/views/auth directory and modify it, such as adding the "Terms of Service" check box. 2. To modify the authentication logic, you need to adjust the methods in RegisterController, LoginController and ResetPasswordController, such as updating the validator() method to verify the added field, or rewriting r

How do I use Laravel's validation system to validate form data? How do I use Laravel's validation system to validate form data? Jun 22, 2025 pm 04:09 PM

Laravelprovidesrobusttoolsforvalidatingformdata.1.Basicvalidationcanbedoneusingthevalidate()methodincontrollers,ensuringfieldsmeetcriterialikerequired,maxlength,oruniquevalues.2.Forcomplexscenarios,formrequestsencapsulatevalidationlogicintodedicatedc

Selecting Specific Columns | Performance Optimization Selecting Specific Columns | Performance Optimization Jun 27, 2025 pm 05:46 PM

Selectingonlyneededcolumnsimprovesperformancebyreducingresourceusage.1.Fetchingallcolumnsincreasesmemory,network,andprocessingoverhead.2.Unnecessarydataretrievalpreventseffectiveindexuse,raisesdiskI/O,andslowsqueryexecution.3.Tooptimize,identifyrequi

How do I escape HTML output in a Blade template using {{{ ... }}}? (Note: rarely used, prefer {{ ... }}) How do I escape HTML output in a Blade template using {{{ ... }}}? (Note: rarely used, prefer {{ ... }}) Jun 23, 2025 pm 07:29 PM

InLaravelBladetemplates,use{{{...}}}todisplayrawHTML.Bladeescapescontentwithin{{...}}usinghtmlspecialchars()topreventXSSattacks.However,triplebracesbypassescaping,renderingHTMLas-is.Thisshouldbeusedsparinglyandonlywithfullytrusteddata.Acceptablecases

How do I mock dependencies in Laravel tests? How do I mock dependencies in Laravel tests? Jun 22, 2025 am 12:42 AM

TomockdependencieseffectivelyinLaravel,usedependencyinjectionforservices,shouldReceive()forfacades,andMockeryforcomplexcases.1.Forinjectedservices,use$this->instance()toreplacetherealclasswithamock.2.ForfacadeslikeMailorCache,useshouldReceive()tod

See all articles