1. 程式人生 > 實用技巧 >cl框架原始碼閱讀(一)

cl框架原始碼閱讀(一)

一.boostorap.php檔案:設定了各框架目錄的常量,自動載入類,並載入公共函式等等。

程式碼:

<?php

/**
*CodeIgniter
*
*AnopensourceapplicationdevelopmentframeworkforPHP
*
*ThiscontentisreleasedundertheMITLicense(MIT)
*
*Copyright(c)2014-2019BritishColumbiaInstituteofTechnology
*Copyright(c)2019-2020CodeIgniterFoundation
*
*Permissionisherebygranted,freeofcharge,toanypersonobtainingacopy
*ofthissoftwareandassociateddocumentationfiles(the"Software"),todeal
*intheSoftwarewithoutrestriction,includingwithoutlimitationtherights
*touse,copy,modify,merge,publish,distribute,sublicense,and/orsell
*copiesoftheSoftware,andtopermitpersonstowhomtheSoftwareis
*furnishedtodoso,subjecttothefollowingconditions:
*
*Theabovecopyrightnoticeandthispermissionnoticeshallbeincludedin
*allcopiesorsubstantialportionsoftheSoftware.
*
*THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,EXPRESSOR
*IMPLIED,INCLUDINGBUTNOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY,
*FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENTSHALLTHE
*AUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHER
*LIABILITY,WHETHERINANACTIONOFCONTRACT,TORTOROTHERWISE,ARISINGFROM,
*OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN
*THESOFTWARE.
*
*@packageCodeIgniter
*@authorCodeIgniterDevTeam
*@copyright2019-2020CodeIgniterFoundation
*@licensehttps://opensource.org/licenses/MITMITLicense
*@linkhttps://codeigniter.com
*@sinceVersion4.0.0
*@filesource
*/

/*
*---------------------------------------------------------------
*SETUPOURPATHCONSTANTS
*---------------------------------------------------------------
*
*Thepathconstantsprovideconvenientaccesstothefolders
*throughouttheapplication.Wehavetosetupthemuphere
*sotheyareavailableintheconfigfilesthatareloaded.
*/

/**
*Thepathtotheapplicationdirectory.
*/
if(!defined('APPPATH'))
{
define('APPPATH',realpath($paths->appDirectory).DIRECTORY_SEPARATOR);
}

/**
*Thepathtotheprojectrootdirectory.JustaboveAPPPATH.
*/
if(!defined('ROOTPATH'))
{
define('ROOTPATH',realpath(APPPATH.'../').DIRECTORY_SEPARATOR);
}

/**
*Thepathtothesystemdirectory.
*/
if(!defined('SYSTEMPATH'))
{
define('SYSTEMPATH',realpath($paths->systemDirectory).DIRECTORY_SEPARATOR);
}

/**
*Thepathtothewritabledirectory.
*/
if(!defined('WRITEPATH'))
{
define('WRITEPATH',realpath($paths->writableDirectory).DIRECTORY_SEPARATOR);
}

/**
*Thepathtothetestsdirectory
*/
if(!defined('TESTPATH'))
{
define('TESTPATH',realpath($paths->testsDirectory).DIRECTORY_SEPARATOR);
}

/*
*---------------------------------------------------------------
*GRABOURCONSTANTS&COMMON
*---------------------------------------------------------------
*/
if(!defined('APP_NAMESPACE'))
{
require_onceAPPPATH.'Config/Constants.php';
}

//Let'sseeifanapp/Common.phpfileexists
if(file_exists(APPPATH.'Common.php'))
{
require_onceAPPPATH.'Common.php';
}

//Requiresystem/Common.php
require_onceSYSTEMPATH.'Common.php';

/*
*---------------------------------------------------------------
*LOADOURAUTOLOADER
*---------------------------------------------------------------
*
*Theautoloaderallowsallofthepiecestoworktogether
*intheframework.Wehavetoloadithere,though,so
*thattheconfigfilescanusethepathconstants.
*/

if(!class_exists(Config\Autoload::class,false))
{
require_onceAPPPATH.'Config/Autoload.php';
require_onceAPPPATH.'Config/Modules.php';
}

require_onceSYSTEMPATH.'Autoloader/Autoloader.php';
require_onceSYSTEMPATH.'Config/BaseService.php';
require_onceAPPPATH.'Config/Services.php';

//UseConfig\ServicesasCodeIgniter\Services
if(!class_exists('CodeIgniter\Services',false))
{
class_alias('Config\Services','CodeIgniter\Services');
}

$loader=CodeIgniter\Services::autoloader();
$loader->initialize(newConfig\Autoload(),newConfig\Modules());//設定了名稱空間、類的對映路徑
$loader->register();//RegistertheloaderwiththeSPLautoloaderstack.//執行自動載入

//NowloadComposer'sifit'savailable
if(is_file(COMPOSER_PATH))
{
/**
*Thepathtothevendordirectory.
*
*Wedonotwanttoenforcethis,sosettheconstantifComposerwasused.
*/
if(!defined('VENDORPATH'))
{
define('VENDORPATH',realpath(ROOTPATH.'vendor').DIRECTORY_SEPARATOR);
}

require_onceCOMPOSER_PATH;
}

//Loadenvironmentsettingsfrom.envfiles
//into$_SERVERand$_ENV
require_onceSYSTEMPATH.'Config/DotEnv.php';

$env=new\CodeIgniter\Config\DotEnv(ROOTPATH);
$env->load();

//AlwaysloadtheURLhelper-
//itshouldbeusedin90%ofapps.
helper('url');

/*
*---------------------------------------------------------------
*GRABOURCODEIGNITERINSTANCE
*---------------------------------------------------------------
*
*TheCodeIgniterclasscontainsthecorefunctionalitytomake
*theapplicationrun,anddoesallofthedirtyworktoget
*thepiecesallworkingtogether.
*/

$appConfig=config(\Config\App::class);
$app=new\CodeIgniter\CodeIgniter($appConfig);
$app->initialize();

return$app;

二.$loader->register();自動載入方法

publicfunctionregister()
{

spl_autoload_extensions('.php,.inc');

//這邊有點看不懂,翻譯解釋:預裝PSR4自動載入器以獲得最佳效能
spl_autoload_register([$this,'loadClass'],true,true);

//Nowprependanotherloaderforthefilesinourclassmap.
$config=is_array($this->classmap)?$this->classmap:[];//根據類的對映路徑載入類

spl_autoload_register(function($class)use($config){
//該function($class)use($config)可以理解為一種for迴圈$class其實是每個$config的鍵
if(empty($config[$class]))
{
returnfalse;
}

include_once$config[$class];
},true,//Throwexception
true//Prepend
);
}

在此列印下$config變數以便檢視。

array(9){
["Psr\Log\AbstractLogger"]=>
string(67)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/AbstractLogger.php"
["Psr\Log\InvalidArgumentException"]=>
string(77)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/InvalidArgumentException.php"
["Psr\Log\LoggerAwareInterface"]=>
string(73)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/LoggerAwareInterface.php"
["Psr\Log\LoggerAwareTrait"]=>
string(69)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/LoggerAwareTrait.php"
["Psr\Log\LoggerInterface"]=>
string(68)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/LoggerInterface.php"
["Psr\Log\LoggerTrait"]=>
string(64)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/LoggerTrait.php"
["Psr\Log\LogLevel"]=>
string(61)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/LogLevel.php"
["Psr\Log\NullLogger"]=>
string(63)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/PSR/Log/NullLogger.php"
["Laminas\Escaper\Escaper"]=>
string(60)"D:\phpstudy_pro\WWW\cl\system\ThirdParty/Escaper/Escaper.php"
}

cl框架自動載入類其實可以這麼理解,在system類AutoloadConfig.php類定義了類的對映物件路徑,並根據設定名稱空間。等框架new不存在的物件時,直接執行spl_autoload_register(function ($class) use ($config) {..該行程式碼,變數物件路徑值直接include_once載入獲得物件。