接下來就是把上篇所定義的Controller 程式的實作

 

一、先把網站內,所有網頁的處理,引導到index.php中作控制

很簡單的設定 [.htaccess] 就可達到這目的了

RewriteEngine on

RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

 

語法是很簡單的

可以嘗試打任一的php網頁,都會導向index.php作處理

但是$_SERVER["REQUEST_URL"]還是使用者要求的網頁喔~~這點很重要

因為開發的物件,就要利用這點來進行撰寫

 

二、撰寫物件,目的是將接收的網址與參數,導向對應的檔案和物件進行處理

 

以下程式是 [class.dispatcher.php] 的內容

 <?

/*

僅在index.php宣告使用,接收傳入參數後,作對應事件之宣告執行

*/

 

class Dispatcher{

    private $handle;

    private $class_path = "/www/htdocs/message/class";

       

    function __construct($event)

    {

        $this->handle = $event;

    }

   

    function handled_event()

    {

   

        /*

        *  擷取$_SERVER["REQUEST_URI"]解析

        *  取得對應的controller file

        */

       

        eregi("(.+)\.php" , basename($_SERVER["REQUEST_URI"]) , $reg);

       

        /*

        *  $reg[1]為檔名

        *  讀取檔案特定目錄下的 controller.xxxx.php

        */

       

        if($reg[1]){

            $file = $this->class_path . "/controller." . $reg[1] . ".php";

            if(is_file($file))

                include_once($this->class_path . "/controller." . $reg[1] . ".php");

            else{

                echo "Controller not exist!";

                exit;

            }

        }else{

            echo "Can't analysis the URL request!";

            exit;

        }

 

        /*

        *  讀取controller.xxx.php中,對應EditMode的動作物件

        *  例如class xxx_add,如不存在則以預設xxx_index物件處理

        */

       

        $name = $reg[1] ."_" . $this->handle;

        if(class_exists($name))

        {

            $handle_obj = new $name($this->handle);

        }else{

            $default_handle = $reg[1] . "_default";

            $handle_obj = new $default_handle();

        }

        return $handle_obj->event_control();

    }

}

?>

到這裡為止,雖然還沒定義到實際運作的class,但是已經具備雛形囉^^

 

三、在 [index.php] 中,加入物件宣告的程式碼,非常很簡潔吧^^

 include_once "class/class.dispatcher.php";

$View = new Dispatcher($_GET['EditMode']);

$View->handled_event();

 

四、測試一下,是否真的有導向和正確運作?

敲入運作的網址 http://www.xxx.com/message/index.php

會出現錯誤訊息

Controller not exist!

簡單的定義一個檔案 [controller.index.php]

 class index_default extends{

    function event_control(){

        echo "test";

    }

}

 

網頁再重新讀取一次,應該成功了吧^^

Controller的雛型架構終於有了,下一章要定義Controller必需的interface和其他部分

加油^^

 

arrow
arrow
    全站熱搜

    miggo 發表在 痞客邦 留言(0) 人氣()