本文实例讲述了PHP从零开始打造自己的MVC框架之类的自动加载实现方法。分享给大家供大家参考,具体如下:
前面介绍了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;
}
}
}
}
|
自动加载的工作原理:
当我们new一个类的时候,如果它不存在,就会触发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.加载函数库
3.启动框架
*/
// 定义当前框架所在的根目录
define('IMOOC', __DIR__);
// 定义框架核心文件所在的目录
define('CORE', IMOOC.'/core');
// 项目文件所在目录
define('APP', IMOOC.'/app');
// 定义项目调试模式
define('DEBUG', true);
// 判断项目是否处于调试状态
if (DEBUG) {
// 设置报错级别:显示所有错误
ini_set('display_error', 'On');
}else{
ini_set('display_error','Off');
}
// 加载函数库
include CORE.'/common/function.php';
// 加载框架核心文件
include CORE.'/imooc.php';
// 注册自动加载
// (当我们new一个不存在的类的时候会触发\\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()会触发load()方法,然后去引入需要的文件。
route.php代码如下:
?
|
1
2
3
4
5
6
7
8
|
<?php
namespace core;
class Route
{
public function __construct(){
p('route ok');
}
}
|
现在我们访问入口文件index.php,会调用Imooc::run方法,预期浏览器会输出:
ok
route ok
至此,项目结构如图:
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/github_26672553/article/details/53872236
相关文章
猜你喜欢



