PHP框架自动加载类文件原理

描述:公司项目PHP用作中间转发层(接收http请求,用 socket跟c++做通信),由于代码没有用到框架,这些东西自然就是之前的人自己写的。最近需要对这个底层进行优化,于是便看了下这部分的代码。

目的:这块代码的主要作用是把主目录下的所有插件类一次性全部加载进来。当使用尚未被定义的类(class)和接口(interface)时自动去加载。通过注册自动加载器,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

实现方法:主要用到PHP函数__autoload()

详细:

 1 error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
 2 set_include_path($_SERVER['Root_Path'] . '/libs' . PATH_SEPARATOR .
 3                  $_SERVER['Root_Path'] . '/lib' . PATH_SEPARATOR .
 4                  get_include_path() );
 5 if (!function_exists('__autoload')) {
 6     function __autoload($className)
 7     {
 8         ///优化包含路径
 9         $path=_getRootPath($className);
10         $revpath=strtr($className, '_', '/'). '.php';
11         $rootpath=$path.$revpath;
12         file_exists($rootpath)?include($rootpath):@include($revpath);
13     }
14 }
15 
16 /**
17  *得到根路径*
18  */
19 function _getRootPath($classname)
20 {
21     $pearpath=$_SERVER["PHP_PEAR_PATH"].'/';
22     $libpath=$_SERVER['Root_Path'] . '/lib/';
23     $libspath=$_SERVER['Root_Path'] . '/libs/';
24 
25     if(strpos($classname,'Zend_')===0) return $pearpath; ///zend 框架路径
26     if(strpos($classname,'DB_')===0 || strpos($classname,'Interface_')===0 || strpos($classname,'Others_')===0  || strpos($classname,'Pay_')===0 || strpos($classname,'PHPMailer_')===0 ) return $libspath;
27     return $libpath;
28 }

其中_getRootPath($classname)函数获取的是类名文件所在的真实目录,根据类名的头字段判断类在哪个目录下;

如果类能在这些目录下找到,类在使用前就会被加载。

 

posted @ 2017-06-06 16:04  zhuojiang  阅读(1207)  评论(0编辑  收藏  举报