PHP框架自動加載類文件原理

描述:公司項目PHP用做中間轉發層(接收http請求,用 socket跟c++作通訊),因爲代碼沒有用到框架,這些東西天然就是以前的人本身寫的。最近須要對這個底層進行優化,因而便看了下這部分的代碼。php

目的:這塊代碼的主要做用是把主目錄下的全部插件類一次性所有加載進來。當使用還沒有被定義的類(class)和接口(interface)時自動去加載。經過註冊自動加載器,腳本引擎在 PHP 出錯失敗前有了最後一個機會加載所需的類。c++

實現方法:主要用到PHP函數__autoload()框架

詳細:socket

 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)函數獲取的是類名文件所在的真實目錄,根據類名的頭字段判斷類在哪一個目錄下;函數

若是類能在這些目錄下找到,類在使用前就會被加載。優化

相關文章
相關標籤/搜索