一般在入库文件中我们会定义一些核心的公共函数、核心类文件、等路径。
自动加载也是要在入库文件中完成的一件事?那么MVC框架是如何实现自动加载的?
利用spl_autoload_register();这一函数实现MVC的自动加载
先简单说下这个函数的作用
spl_autoload_register — 注册__autoload()函数
说明
bool spl_autoload_register ([ callback $autoload_function ] )
将函数注册到SPL __autoload函数栈中。如果该栈中的函数尚未激活,则激活它们。
bool spl_autoload_register ([ callback $autoload_function ] )
将函数注册到SPL __autoload函数栈中。如果该栈中的函数尚未激活,则激活它们。
如果在你的程序中已经实现了__autoload函数,它必须显式注册到__autoload栈中。因为
spl_autoload_register()函数会将Zend Engine中的__autoload函数取代为spl_autoload()或
spl_autoload_call()。
参数
autoload_function
欲注册的自动装载函数。如果没有提供任何参数,则自动注册autoload的默认实现函数
欲注册的自动装载函数。如果没有提供任何参数,则自动注册autoload的默认实现函数
spl_autoload()。
返回值
如果成功则返回 TRUE,失败则返回 FALSE。
如果成功则返回 TRUE,失败则返回 FALSE。
注:SPL是Standard PHP Library(标准PHP库)的缩写。它是PHP5引入的一个扩展库,其主要功能包括autoload机制的实现及包括各种Iterator接口或类。SPL autoload机制的实现是通过将函数指针autoload_func指向自己实现的具有自动装载功能的函数来实现的。SPL有两个不同的函数spl_autoload, spl_autoload_call,通过将autoload_func指向这两个不同的函数地址来实现不同的自动加载机制。
spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。
spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。
spl_autoload_register('\core\myFrame::load'); //这是自动加载类
\core\myFrame::run(); //加载路由方法
值得注意的是 \core\myFrame::run();这个方法是没有在入库文件所调用的,那他是如何调用的呢?
前面提到spl_autoload_register();就起作用了他会自动调用我\core\myFrame::load这个方法如果改方法或类存在则传入该方法类的所在路径
isset 检测改路径是否已被加载,如果加载则直接返回true
未加载则将该类的路径拼接好,并引入改类文件存并且将该路径存入静态变量中以供下次调用。
\core\myFrame::run()
public static $classMap = array();
/**
* 自动加在类库
*/
static public function load($class){
echo $class;die;
if (isset($classMap[$class])) {
return true;
} else {
$class = str_replace('\\', '/', $class);
$file = MY_FRAME.'/'.$class.'.php';
if (is_file($file)) {
include $file;
self::$classMap[$class] = $class;
} else {
return false;
}
}
}
static public function run(){
\core\lib\log::init(); //加载核心日志类
\core\lib\log::log(array('name'=>'zhangsan','age'=>14));
$route = new \core\lib\route(); //加载路由类
$controller = $route->controller;
$action = $route->action;
$controlleFile = APP.'/controller/'.$controller.'Controller.php';
$controllerClass = '\\'.MODULE.'\controller\\'.$controller.'Controller';
if (is_file($controlleFile)) {
include $controlleFile;
$ctrl = new $controllerClass();
$ctrl->$action() ;
\core\lib\log::log('controller:'.$controllerClass.'.action'.$action);
} else {
throw new \Exception("找不到控制器".$controller);
}
}
run方法是一个核心的路由方法 由上述自动加载的方法调用路由方法,完成自动加载。