控制器(Controller)的作用通常是在取得模型(Model)中資料並交給視圖(View)去顯示,那開發中我們該如何去寫呢?

1.建立Controller的類別檔案,我這裡檔案名稱為MatchController.class.php(推薦學習:PHP程式設計從入門到精通)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php
class MatchController{
public function listAction(){
header('Content-Type: text/html;charset=utf-8');
require './Factory. class .php';
$m_match = Factory::M('MatchModel');
$match_list = $m_match ->getList();
require './template/match_list_v.html';
}
public function removeAction(){
}
|
登入後複製
2.在入口檔案中實例化控制器物件(前端控制器或請求分發器),檔案名稱index.php
為了能讓index.php去執行我們要操作的動作,應該傳給index.php一些參數,來告訴入口文件怎麼做。
假如我們要在比賽清單(比賽Controller)中刪除一則比賽訊息,可以這樣傳給index.php:
1 | index.php?c=match&a=remove&id=N
|
登入後複製
對應的HTML檔案應該這樣寫:

index.php:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
$default_action = 'list';
$a = isset( $_GET ['a'])? $_GET ['a']: $default_action ;
require './MatchController. class .php';
$controller = new MatchController();
$action_name = $a .'Action';
$controller -> $action_name ();
|
登入後複製
以上是php控制器的方法在哪的詳細內容。更多資訊請關注PHP中文網其他相關文章!