MVC 入門

許桔

MVC架構概念

MVC架構概念 - 延伸

預處理

1. 建置sql

2. 下載檔案

3. 完成檔案

切 Model

  1. 優化你和資料庫溝通的程式(用function包起來)
  2. 建立一個Model資料夾,並新增一個php檔
  3. 把所有php的function放進去
  4. require你model底下的php檔

切 View

  1. View只負責顯示
  2. 建立一個View資料夾,有幾個頁面就切幾個View的php
  3. 各別頁面require

Controller

  1. 用GET參數來控制Controller的頁面
  2. 判斷完後引入對應的Model,轉交給View顯示
  3. 之後程式一定要加註解,不然你過一個禮拜來看....

Controller


<?php
require("db_connection.php");
require("model/model.php");

//判斷網址帶來的GET
if( isset( $_GET['action'] ) ){
	switch($_GET['action']){
		case 'show': //顯示資料
			break;
			
		case 'insert' : //新增資料
			break;

                ....
			
		default : //找不到頁面!
			require("view/error.php");
	}
}else{
	require("view/error.php");
}

Controller


        ....        

	switch($_GET['action']){
		case 'show': //顯示資料
                        $prepareSQL = "SELECT * FROM student";
			$executeSQL = array();
			$sql = $model->getDataSQL($prepareSQL, $executeSQL);
                        require("view/show.php");
			break;
			

                .....

			
		default : //找不到頁面!
			require("view/error.php");
	}
<form action="insert.php" method="POST">

<form action="?action=insert" method="POST">

Clean Model

class model{
        
        //告知資料庫在哪
	function __construct(PDO $dbh){
		$this->dbh = $dbh;
	}


        
	function getDataSQL($prepareSQL, $executeSQL) { //顯示資料
		$dbh = $this->dbh;
		$sql = $dbh->prepare($prepareSQL);
		$sql->execute($executeSQL);
		return $sql->fetchAll();
	}


    .......

用Class把Model包起來

調整 Controller


if(isset($_GET['action'])){


	$model = new model($dbh);  


	switch($_GET['action']){
		case 'show': //顯示資料
                        $prepareSQL = "SELECT * FROM student";
			$executeSQL = array();
			$sql = $model->getDataSQL($prepareSQL, $executeSQL);
                        require("view/show.php");
			break;
			

                .....

引入model統一呼叫db,避免各別重複呼叫db物件

基礎MVC完成

Made with Slides.com