本文實例講述了PHP從零開始打造自己的MVC框架之類的自動加載實現(xiàn)方法。分享給大家供大家參考,具體如下:
前面介紹了MVC框架的入口文件,接下來我們希望完成一個“自動加載類”的功能,我們把這個功能放到Imooc
這個基礎類當中。
core\imooc.php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<?php namespace core; class Imooc { public static $classMap = array (); static public function run() { p( 'ok' ); $route = new \core\route(); } /* 自動加載的功能 */ static public function load( $class ) { // 自動加載類庫 // new \core\Route() // $class = '\core\Route' // IMOOC.'/core/route.php' if (isset( $classMap [ $class ])){ return true; } else { $class = str_replace ( '\\' , '/' , $class ); $file = IMOOC. '/' . $class . '.php' ; if ( is_file ( $file )) { include $file ; self:: $classMap [ $class ] = $class ; } else { return false; } } } } |
上面代碼中,load()
方法的主要功能就是自動加載類庫。
自動加載的工作原理:
當我們new
一個類的時候,如果它不存在,就會觸發(fā)spl_autoload_register
注冊的方法,然后通過這個方法去引入要實例化的類
1
|
spl_autoload_register( '\core\Imooc::load' ); |
我們在入口文件index.php中注冊:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?php /* 入口文件 1.定義常量 2.加載函數(shù)庫 3.啟動框架 */ // 定義當前框架所在的根目錄 define( 'IMOOC' , __DIR__); // 定義框架核心文件所在的目錄 define( 'CORE' , IMOOC. '/core' ); // 項目文件所在目錄 define( 'APP' , IMOOC. '/app' ); // 定義項目調試模式 define( 'DEBUG' , true); // 判斷項目是否處于調試狀態(tài) if (DEBUG) { // 設置報錯級別:顯示所有錯誤 ini_set ( 'display_error' , 'On' ); } else { ini_set ( 'display_error' , 'Off' ); } // 加載函數(shù)庫 include CORE. '/common/function.php' ; // 加載框架核心文件 include CORE. '/imooc.php' ; // 注冊自動加載 // (當我們new一個不存在的類的時候會觸發(fā)\core\Imooc::load) spl_autoload_register( '\core\Imooc::load' ); \core\Imooc::run(); |
所以,我們在run
方法實例化route
類的時候并沒有手動引入該類文件
1
2
3
4
5
|
static public function run() { p( 'ok' ); $route = new \core\route(); } |
上面代碼,new \core\route()
會觸發(fā)load()
方法,然后去引入需要的文件。
route.php代碼如下:
1
2
3
4
5
6
7
8
|
<?php namespace core; class Route { public function __construct(){ p( 'route ok' ); } } |
現(xiàn)在我們訪問入口文件index.php,會調用Imooc::run
方法,預期瀏覽器會輸出:
ok
route ok
至此,項目結構如圖:
希望本文所述對大家PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/github_26672553/article/details/53872236