只要MVC不要Framework

這段時間在學著使用Framework像是Zend FrameworkCodeIgniter,至於哪一個好哪一個壞就不在這多說,網路上有太多 Framework 的比較,用了Framework之後我覺得我只要單純的MVC的架構而已,需要用到一個 Framework 來綁住自己嗎?

雖然用Framework有很多好處像是、快速、簡單、有很多強大的LIB可以用,但是我不想被一個Framework綁住,效能也是一個原因。(其實是受了Rasmus Lerdorf的影響 XD)

所以打算自己做一個控制器的class來用就好,並且可以看Zend FrameworkCodeIgniter的code來學習它們是怎麼做的,另外未來如果自己需要什麼功能就看看各Framework的lib有無提供class直接抓來用,或是自己寫一個也是可以。

目錄架構

1
2
3
4
5
6
專案目錄\
libraries\
controllers\
views\
index.php
.htaccess

CODE

.htaccess

1
2
3
4
5
6
7
.htaccess
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^.*$ index<span style="color:#008c00; ">.</span>php [NC,L]

libraries\Controller.php

1
2
3
4
5
6
7
8
9
    class Controller {
        function Controller($_action){
            if(empty($_action)) $_action='index';
            $this->{$_action}();
        }
        function view($file,$data=false){
            return require $_SERVER["DOCUMENT_ROOT"].'/views/'.$file<span style="color:#008c00; ">.</span>'.php';
        }
    }

index.php

1
2
3
4
5
6
7
8
9
10
11
    define('APP_REAL_PATH', str_replace('\\', '/', dirname(__FILE__)));
    require(APP_REAL_PATH .'/libraries/Controller<span style="color:#008c00; ">.</span>php'); 
 
    // get control & action
    $_REDIRECT_URL = explode("/",$_SERVER["REDIRECT_URL"]);
    $_control = ucwords($_REDIRECT_URL[<span style="color:#008c00; ">1</span>]);
    $_action = ucwords($_REDIRECT_URL[<span style="color:#008c00; ">2</span>]); 
 
    // load control
    require(APP_REAL_PATH .'/controllers/'.strtolower($_control).'.php');
    $control = new $_control($_action);

controllers\test.php

1
2
3
4
5
6
7
8
9
10
11
12
    class Test extends Controller {
        function test($_action){
            parent::Controller($_action);
        }
        function index(){
            $data = array('hello','word');
            $this->view('test',$data);
        }
        function hello(){
            echo 'hello';
        }
    }

views\test.php

1
    echo $data[0].','.$data[1];

輸出

1
2
3
4
5
http://yourdomain/test/ or http://yourdomain/test/index
=> hello,word
 
http://yourdomain/test/hello
=> hello

以上我寫的程式或許不好或是有需要改進的地方,歡迎各方高手來指正。

說明

所有的要求都會經過index.php來做控制器的分配
例如:http://yourdomain/test/index 這網址的test為控制器(Control),index為動作(Action)。

結論

其實MVC就像下面參考資料網站裡提到 "MVC 是一種程式架構的觀念,它與軟體需求或規格無關,其意義甚至可以簡化到視為 programmer 撰寫程式時的「良好習慣」" ,所以並不一定要用CLASS方式來達成MVC的架構,只要遵循MVC的精神一樣也可以屬於適合自己的MVC架構。

像是 http://yourdomain/index.php?C=test&A=index 這樣的網址,在index.php裡抓取$_GET['C']為控制器,$_GET['A']為動作,然後再去載入某一個控制器並做什麼動作,最後再載入需要的頁面(html),這樣不也可以是MVC的架構嗎?

參考資料

Related Posts with Thumbnails

相關文章