php架構開發2(SPL庫和controller)

來源:互聯網
上載者:User
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官網上去尋找相應函數的用法。

下一節相會對視圖作一個簡單的介紹。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.