php架構開發二(SPL庫和controller)
根據上話的目錄結構(如果不清楚的可以看上一篇)。我在simple檔案夾內建立了一個simple.php.
require 'includes/exceptions.php';require 'includes/autoloader.php';session_start();
//$view = new view();lib::set_item('controller' , new controller());lib::get_item('controller' , lib::PERSIST_STORGE)->render();//$content = $view->finish();
這一章主要是講SPL,所以我們只看第二行的autoloader.php.當我們在index.php中加入
require 'simple/simple.php';
之後。
我們看一下autoloader.php的源碼
這個類都是靜態方法,當引用這個PHP檔案後,程式會自動載入這三個檔案夾下的內容,這樣我們不用重複去required 或include。如果對SPL有不瞭解的,可以直接去百度,這裡只是告訴大家,這個SPL作用相當廣。
然後在includes檔案夾內建立一個lib.php
這個類目前只用於設定SESSION相關的內容。
當執行到lib::set_item('controller' , new controller());時,這裡建立了一個控制器對象,並對象存入SESSION中。
controller.php
parts = array();$this->analysis();}public function analysis(){$path_info = $_SERVER['PATH_INFO'];if(substr($path_info , 0 , 1) == '/'){$path_info = substr($path_info , 1);}$parts = explode('/' , $path_info);if(empty($parts[0])) $parts[0] = 'index';if(empty($parts[1])) $parts[1] = 'demo';$this->parts = $parts;array_shift($parts);array_shift($parts);$this->params = $parts;}public function render(){if(!class_exists($this->parts[0])){throw new ControllerDoesntExistsException($this->parts[0] . ' not exists!');}if(!method_exists($this->parts[0] , $this->parts[1])){throw new ActionDoesntExistsException($this->parts[0] . 'of ' . $this->parts[1] . ' not exists!');}$new_controller = new $this->parts[0];$called = call_user_func_array(array($new_controller , $this->parts[1]) , $this->params);if($called === false){throw new ActionFailedException($this->parts[0] . 'of ' . $this->parts[1] . ' failed to excute property!');}}}
這個類只用PATH_INFO模式來擷取調用的控制器和ACTION,並將參數傳遞到相應的ACTION方法裡。當controller初始化之後,會自動分析PATH_INFO的內容,
lib::get_item('controller' , lib::PERSIST_STORGE)->render();
然後調用render()就會在相應的控制器目錄找到控制器和ACTION。
例如我在controller檔案夾內建立一個index.php
那麼執行http://localhost/index.php/index/demo就會輸出"sdfsdf";(這是我的本地路徑)。
以上代碼難度不高,如果沒有看懂的同學,請Q我,也可以去PHP官網上去尋找相應函數的用法。
下一節相會對視圖作一個簡單的介紹。