列出一個超級簡單的MVC結構實現,甚至連數據庫都用了一個內置的固定數組,雖然簡單,但其實眾多的PHP Framework核心實現的思想應該和這個是差不多的,只不過一些framework提供了更多的方便開發者使用的工具,對於初次有心瞭解MVC者來說,這是一個簡單啟蒙,
希望能夠從簡單框架的開發中學習到更多的PHP設計思想和方法,而不是只會操作工具來完成。

名 詞 解 釋 :PHP(PHP:Hypertext Preprocessor)
是一種在電腦上執行的腳本語言,主要用途是在於處理動態互動網頁機制,也包含了命令列執行介面(command line interface),或者產生圖形使用者介面(GUI)程式…more

Controller.php

include ‘Model.php’;
include ‘View.php’;

class Controller {
private $model     = ”;
private $view     = ”;

public function Controller(){
$this->model    =    new Model();
$this->view        =    new View();
}

public function doAction( $method = ‘defaultMethod’, $params = array() ){
if( empty($method) ){
$this->defaultMethod();
}else if( method_exists($this, $method) ){
call_user_func(array($this, $method), $params);
}else{
$this->nonexisting_method();
}
}

public function link_page($name = ”){
$links = $this->model->getLinks();
$this->view->display($links);

$result = $this->model->getResult($name);
$this->view->display($result);
}

public function defaultMethod(){
$this->br();
echo “This is the default method. “;
}

public function nonexisting_method(){
$this->br();
echo “This is the noexisting method. “;
}

public function br(){
echo “<br />”;
}
}
$controller = new Controller();
$controller->doAction(‘link_page’, ‘b’);
$controller->doAction();
Model.php
Code
class Model {
private $database = array(
“a”    =>    “hello world”,
“b”    =>    “ok well done”,
“c”    =>    “good bye”,
);

//@TODO connect the database

//run the query and get the result
public function getResult($name){
if( empty($name) ){
return FALSE;
}

if( in_array($name, array_keys( $this->database ) ) ){
return $this->database[$name];
}
}

public function getLinks(){
$links = “<a href=’#’>Link A</a>&nbsp;&nbsp;”;
$links.= “<a href=’#’>Link B</a>&nbsp;&nbsp;”;
$links.= “<a href=’#’>Link C</a>&nbsp;&nbsp;”;

return $links;
}
}

View.php
class View {

public function display($output){
//        ob_start();

echo $output;
}

}

更多

Related Posts

專欄文摘

淺述網路視訊在網頁設計中運用

動態的視訊比靜態的圖片更生動,表達的訊息更多。但是目前網路上的視訊其實 Read more...

專欄文摘

如何預先做好網站資料庫的安全防護機制

先分3點從全局來看 對作業系統的安全需求:防止對DBMS的非法訪問和修 Read more...

專欄文摘

從零打造新品牌須先建立信仰粉絲(一)

新品牌是指剛進入市場的產品的品牌或原有的產品經過改進以後賦予的新的品牌 Read more...