標籤:reflect ade getc dex on() bsp contain row container
但有一問題沒有解決, 就是在include前判斷檔案是否存在的問題.
| 12345678910111213 |
set_include_path(‘aa‘ . PATH_SEPARATOR . get_include_path());function __autoload($className){ //如果加這個檢測, 因為此檔案不在目前的目錄下,它就會檢測不到檔案存在, //但include是能成功的 if (file_exists($className . ‘.php‘)) { include_once($className . ‘.php‘); } else { exit(‘no file‘); }} $a = new Acls(); |
第二種方案用spl自動載入,這裡具體說一下這個.
spl_autoload_register()
一個簡單的例子
| 12345678910111213 |
set_include_path(‘aa‘ . PATH_SEPARATOR . get_include_path());//function __autoload($className)//{// if (file_exists($className . ‘.php‘)) {// include_once($className . ‘.php‘);// } else {// exit(‘no file‘);// }//} spl_autoload_register(); $a = new Acls(); |
spl_autoload_register()會自動先調用spl_autoload()在路徑中尋找具有小寫檔案名稱的".php"程式.預設尋找的副檔名還有".ini",還可以用spl_autoload_extenstions()註冊副檔名.
在找不到的清況下,還可以通過自己定義函數尋找
如
function loader1($class)
{
//自己寫一些載入的代碼
}
function loader2($class)
{
//當loader1()找不到時,我來找
}
spl_autoload_register(‘loader1‘);
spl_autoload_register(‘loader2‘);
還可以更多........
MVC架構是如何?自動載入的
首先設定路徑
‘include‘ => array( ‘application/catalog/controllers‘, ‘application/catalog/models‘, ),
$include = array(‘application/controllers‘, ‘application/models‘, ‘application/library‘);
set_include_path(get_include_path() . PATH_SEPARATOR .implode(PATH_SEPARATOR, $config[‘include‘]));
在擷取URL,解析出控制器與方法.
然後設定自動載入
| 123456789101112131415161718 |
class Loader{ /** * 自動載入類 * @param $class 類名 */ public static function autoload($class) { $path = ‘‘; $path = str_replace(‘_‘, ‘/‘, $class) . ‘.php‘; include_once($path); }} /** * sql自動載入 */spl_autoload_register(array(‘Loader‘, ‘autoload‘)); |
路由,執行個體化控制器,調用方法,你寫的東西就開始執行了
| 12345678910111213141516 |
/** * 路由 */public function route(){ if (class_exists($this->getController())) { $rc = new ReflectionClass($this->getController()); if ($rc->hasMethod($this->getAction())) { $controller = $rc->newInstance(); $method = $rc->getMethod($this->getAction()); $method->invoke($controller); } else throw new Exception(‘no action‘); } else throw new Exception(‘no controller‘);} |
php自動載方法有兩種.