MVC模式(Model-View-Controller)是軟件工程中的一種軟件架構模式,把軟件系統分爲三個基本部分:模型(Model)、視圖(View)和控制器(Controller)。php
MVC模式的目的是實現一種動態的程序設計,使後續對程序的修改和擴展簡化,而且使程序某一部分的重複利用成爲可能。除此以外,此模式經過對複雜度的簡化,使程序結構更加直觀。軟件系統經過對自身基本部份分離的同時也賦予了各個基本部分應有的功能。html
簡而言之,mysql
網絡上有大量優秀的MVC框架可供使用,本教程並非爲了開發一個全面的、終極的MVC框架解決方案,而是將它看做是一個很好的從內部學習PHP的機會,在此過程當中,你將學習面向對象編程和MVC設計模式,並學習到開發中的一些注意事項。git
更重要的是,你能夠徹底控制你的框架,並將你的想法融入到你開發的框架中。雖然不必定是作好的,可是你能夠按照你的方式去開發功能和模塊。github
在開始開發前,讓咱們先來把項目創建好,假設咱們創建的項目爲 todo,MVC的框架能夠命名爲 FastPHP,那麼接下來的第一步就是把目錄結構先設置好。sql
雖然在這個教程中不會使用到上面的全部的目錄,可是爲了之後程序的可拓展性,在一開始就把程序目錄設置好使很是必要的。下面就具體說說每一個目錄的做用:數據庫
在目錄設置好之後,咱們接下來就要來規定一下代碼的規範:編程
上述的一些規則是爲了能在程序中更好的進行互相的調用。接下來就開始真正的PHP MVC編程了。設計模式
將全部的數據請求都重定向 index.php 文件,在 todo 目錄下新建一個 .htaccess 文件,文件內容爲:數組
<IfModule mod_rewrite.c> RewriteEngine On # 確保請求路徑不是一個文件名或目錄 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 重定向全部請求到 index.php?url=PATHNAME RewriteRule ^(.*)$ index.php?url=$1 [PT,L] </IfModule>
作完上面的操做,就應該知道咱們須要作什麼了,沒錯!在 public 目錄下添加 index.php 文件,文件內容爲:
<?php // 應用目錄爲當前目錄 define('APP_PATH', __DIR__.'/'); // 開啓調試模式 define('APP_DEBUG', true); // 加載框架 require './fastphp/FastPHP.php';
在 index.php 中,咱們對 fastphp 文件夾下的 FastPHP.php 發起了請求,那麼 FastPHP.php 這個啓動文件中到底會包含哪些內容呢?
<?php // 初始化常量 defined('ROOT') or define('ROOT', __DIR__.'/'); defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']).'/'); defined('APP_DEBUG') or define('APP_DEBUG', false); defined('CONFIG_PATH') or define('CONFIG_PATH', APP_PATH.'config/'); defined('RUNTIME_PATH') or define('RUNTIME_PATH', APP_PATH.'runtime/'); // 類文件擴展名 const EXT = '.class.php'; // 包含配置文件 require APP_PATH . 'config/config.php'; // 包含核心框架類 require ROOT . 'Core.php'; // 實例化核心類 $fast = new Fast; $fast->run();
先來看看config文件下的 config .php 文件,該文件的主要做用是設置一些程序的配置項及數據庫鏈接等,主要內容爲:
<?php /** 變量配置 **/ define('DB_NAME', 'todo'); define('DB_USER', 'root'); define('DB_PASSWORD', 'root'); define('DB_HOST', 'localhost');
應該說 config.php 涉及到的內容並很少,不過是一些基礎數據庫的設置,再來看看 fastphp下的共用框架入口文件 Core.php 應該怎麼寫。
<?php /** * FastPHP核心框架 */ class Fast { // 運行程序 function run() { spl_autoload_register(array($this, 'loadClass')); $this->setReporting(); $this->removeMagicQuotes(); $this->unregisterGlobals(); $this->callHook(); } // 主請求方法,主要目的是拆分URL請求 function callHook() { if (!empty($_GET['url'])){ $url = $_GET['url']; $urlArray = explode("/",$url); // 獲取控制器名 $controllerName = ucfirst(empty($urlArray[0]) ? 'Index' : $urlArray[0]); $controller = $controllerName . 'Controller'; // 獲取動做名 array_shift($urlArray); $action = empty($urlArray[0]) ? 'index' : $urlArray[0]; //獲取URL參數 array_shift($urlArray); $queryString = empty($urlArray) ? array() : $urlArray; } // 數據爲空的處理 $action = empty($action) ? 'index' : $action; $queryString = empty($queryString) ? array() : $queryString; // 實例化控制器 $int = new $controller($controllerName, $action); // 若是控制器存和動做存在,這調用並傳入URL參數 if ((int)method_exists($controller, $action)) { call_user_func_array(array($int, $action), $queryString); } else { exit($controller . "控制器不存在"); } } // 檢測開發環境 function setReporting() { if (APP_DEBUG == true) { error_reporting(E_ALL); ini_set('display_errors','On'); } else { error_reporting(E_ALL); ini_set('display_errors','Off'); ini_set('log_errors', 'On'); ini_set('error_log', RUNTIME_PATH. 'logs/error.log'); } } // 刪除敏感字符 function stripSlashesDeep($value) { $value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value); return $value; } // 檢測敏感字符並刪除 function removeMagicQuotes() { if ( get_magic_quotes_gpc() ) { $_GET = stripSlashesDeep($_GET ); $_POST = stripSlashesDeep($_POST ); $_COOKIE = stripSlashesDeep($_COOKIE); $_SESSION = stripSlashesDeep($_SESSION); } } // 檢測自定義全局變量(register globals)並移除 function unregisterGlobals() { if (ini_get('register_globals')) { $array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES'); foreach ($array as $value) { foreach ($GLOBALS[$value] as $key => $var) { if ($var === $GLOBALS[$key]) { unset($GLOBALS[$key]); } } } } } //自動加載控制器和模型類 static function loadClass($class) { $frameworks = ROOT . $class . EXT; $controllers = APP_PATH . 'application/controllers/' . $class . EXT; $models = APP_PATH . 'application/models/' . $class . EXT; if (file_exists($frameworks)) { // 加載框架核心類 include $frameworks; } elseif (file_exists($controllers)) { // 加載應用控制器類 include $controllers; } elseif (file_exists($models)) { //加載應用模型類 include $models; } else { /* 錯誤代碼 */ } } }
下面重點講解主請求方法 callHook(),首先咱們想看看咱們的 URL 會這樣:
yoursite.com/controllerName/actionName/queryString
callHook()的做用就是,從全局變量 $_GET['url']變量中獲取 URL,並將其分割成三部分:$controller、$action 和 $queryString。
例如,URL連接爲:todo.com/item/view/1/first-item,那麼
分割完成後,會實例化一個新的控制器:$controller.’Controller’(其中「.」是連字符),並調用其方法 $action。
接下來的操做就是在 fastphp 中創建程序所需的基類,包括控制器、模型和視圖的基類。
新建控制器基類爲 Controller.class.php,控制器的主要功能就是總調度,具體具體內容以下:
<?php /** * 控制器基類 */ class Controller { protected $_controller; protected $_action; protected $_view; // 構造函數,初始化屬性,並實例化對應模型 function __construct($controller, $action) { $this->_controller = $controller; $this->_action = $action; $this->_view = new View($controller, $action); } function set($name, $value) { $this->_view->set($name, $value); } function __destruct() { $this->_view->render(); } }
Controller 類實現全部控制器、模型和視圖(View類)的通訊。在執行析構函數時,咱們能夠調用 render() 來顯示視圖(view)文件。
新建模型基類爲 Model.class.php,模型基類 Model.class.php 代碼以下:
<?php class Model extends Sql { protected $_model; protected $_table; function __construct() { // 鏈接數據庫 $this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME); // 轉換模型+Model爲模型名稱 // 獲取對象所屬類的名稱 $this->_model = get_class($this); $this->_model = rtrim($this->_model, 'Model'); // 數據庫表名與類名一致 $this->_table = strtolower($this->_model); } function __destruct() { } }
考慮到模型須要對數據庫進行處理,因此單獨創建一個數據庫基類 Sql.class.php,模型基類繼承 Sql.class.php,代碼以下:
<?php class Sql { protected $_dbHandle; protected $_result; /** 鏈接數據庫 **/ function connect($address, $account, $pwd, $name) { $this->_dbHandle = @mysql_connect($address, $account, $pwd); if ($this->_dbHandle != 0) { if (mysql_select_db($name, $this->_dbHandle)) { return 1; } else { return 0; } } else { return 0; } } /** 從數據庫斷開 **/ function disconnect() { if (@mysql_close($this->_dbHandle) != 0) { return 1; } else { return 0; } } /** 查詢全部 **/ function selectAll() { $query = 'select * from `'.$this->_table.'`'; return $this->query($query); } /** 根據條件 (id) 查詢 **/ function select($id) { $query = 'select * from `'.$this->_table.'` where `id` = \''.mysql_real_escape_string($id).'\''; return $this->query($query, 1); } /** 根據條件 (id) 刪除 **/ function delete($id) { $query = 'delete from `'.$this->_table.'` where `id` = \''.mysql_real_escape_string($id).'\''; return $this->query($query); } /** 自定義SQL查詢 **/ function query($query, $singleResult = 0) { $this->_result = mysql_query($query, $this->_dbHandle); if (preg_match("/select/i",$query)) { $result = array(); $table = array(); $field = array(); $tempResults = array(); $numOfFields = mysql_num_fields($this->_result); for ($i = 0; $i < $numOfFields; ++$i) { array_push($table,mysql_field_table($this->_result, $i)); array_push($field,mysql_field_name($this->_result, $i)); } while ($row = mysql_fetch_row($this->_result)) { for ($i = 0;$i < $numOfFields; ++$i) { $table[$i] = ucfirst($table[$i]); $tempResults[$table[$i]][$field[$i]] = $row[$i]; } if ($singleResult == 1) { mysql_free_result($this->_result); return $tempResults; } array_push($result,$tempResults); } mysql_free_result($this->_result); return($result); } } /** 獲取記錄數 **/ function getNumRows() { return mysql_num_rows($this->_result); } /** 釋放查詢資源 **/ function freeResult() { mysql_free_result($this->_result); } /** 獲取錯誤信息 **/ function getError() { return mysql_error($this->_dbHandle); } }
應該說,Sql.class.php 是框架的核心部分。爲何?由於經過它,咱們建立了一個 SQL 抽象層,能夠大大減小了數據庫的編程工做。connect() 和 disconnect() 方法比較簡單,很少作說明,重點講講 Query查詢。假設咱們有以下的一段 SQL 查詢語句:
SELECT table1.field1, table1.field2, table2.field3, table2.field4 FROM table1,table2 WHERE …
若是使用上面的 SQL 基類,首先要作的工做是選出要輸出的字段以及相對應的數據表,而後把它們放到數組中,其中,$field 和 $table 使用相同的索引值。在上面的例子中,它們是這樣的:
$field = array(field1,field2,field3,field4); $table = array(table1,table1,table2,table2);
腳本會展開全部的數據行,並將數據錶轉換成一個模型名(如去除複數和首字母大寫)。查詢結果最終保存在一個多維數組中,而後返回,格式相似於:$var['modelName']['fieldName']。這樣輸出方式能夠很是便於在視圖中使用這些元素。
視圖類 View.class.php 內容以下:
<?php /** * 視圖基類 */ class View { protected $variables = array(); protected $_controller; protected $_action; function __construct($controller, $action) { $this->_controller = $controller; $this->_action = $action; } /** 設置變量方法 **/ function set($name, $value) { $this->variables[$name] = $value; } /** 顯示 **/ function render() { extract($this->variables); $defaultHeader = APP_PATH . 'application/views/header.php'; $defaultFooter = APP_PATH . 'application/views/footer.php'; $controllerHeader = APP_PATH . 'application/views/' . $this->_controller . '/header.php'; $controllerFooter = APP_PATH . 'application/views/' . $this->_controller . '/footer.php'; // 頁頭文件 if (file_exists($controllerHeader)) { include ($controllerHeader); } else { include ($defaultHeader); } // 頁內容文件 include (APP_PATH . 'application/views/' . $this->_controller . '/' . $this->_action . '.php'); // 頁腳文件 if (file_exists($controllerFooter)) { include ($controllerFooter); } else { include ($defaultFooter); } } }
這樣咱們的核心的PHP MVC框架就編寫完成了,下面咱們開始編寫應用來測試框架功能。
在 SQL 中新建一個 todo 數據庫,使用下面的語句增長 item 數據表並插入2條記錄:
CREATE TABLE `items` ( `id` int(11) NOT NULL auto_increment, `item_name` varchar(255) NOT NULL, PRIMARY KEY (`id`) ); INSERT INTO `items` VALUES(1, 'Hello World.'); INSERT INTO `items` VALUES(2, 'Lets go!');
而後,咱們還須要在 models 目錄中建立一個 ItemModel.php 模型,內容以下:
<?php class ItemModel extends Model { /** 新增數據 **/ function add($value){ $query = 'insert into `'.$this->_table.'` (item_name) values (\''.mysql_real_escape_string($value).'\')'; return $this->query($query); } /** 新增數據 **/ function update($id, $value){ $query = 'update `'.$this->_table.'` set item_name = \''.mysql_real_escape_string($value).'\' where `id` = \''.mysql_real_escape_string($id).'\''; return $this->query($query); } }
模型內容爲空。由於 Item 模型繼承了 Model,因此它擁有 Model 的全部功能。
在 controllers 目錄下建立一個 ItemsController.php 控制器,內容以下:
<?php class ItemController extends Controller { // 首頁方法,測試框架自定義DB查詢 function index() { $item = new ItemModel; $this->set('title', '所有條目'); $this->set('todo', $item->query('select * from item')); } // 添加記錄,測試框架DB記錄建立(Create) function add() { $value = $_POST['value']; $item = new ItemModel; $this->set('title', '添加成功'); $this->set('todo', $item->add($value)); } // 查看記錄,測試框架DB記錄讀取(Read) function view($id = null,$name = null) { $item = new ItemModel; $this->set('title', '正在查看'. $name); $this->set('todo', $item->select($id)); } // 更新記錄,測試框架DB記錄更新(Update) function update() { $id = $_POST['id']; $value = $_POST['value']; $item = new ItemModel; $this->set('title', '修改爲功'); $this->set('todo', $item->update($id, $value)); } // 刪除記錄,測試框架DB記錄刪除(Delete) function delete($id = null) { $item = new ItemModel; $this->set('title','刪除成功'); $this->set('todo',$item->delete($id)); } }
在 views 目錄下新建 header.php 和 footer.php 兩個頁頭頁腳模板,內容以下。
header.php,內容:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $title?></title> <style> .item { width:400px; } input { color:#222222; font-family:georgia,times; font-size:24px; font-weight:normal; line-height:1.2em; color:black; } a { color:#222222; font-family:georgia,times; font-size:24px; font-weight:normal; line-height:1.2em; color:black; text-decoration:none; } a:hover { background-color:#BCFC3D; } h1 { color:#000000; font-size:41px; letter-spacing:-2px; line-height:1em; font-family:helvetica,arial,sans-serif; border-bottom:1px dotted #cccccc; } h2 { color:#000000; font-size:34px; letter-spacing:-2px; line-height:1em; font-family:helvetica,arial,sans-serif; } </style> </head> <body> <h1><?php echo $title?></h1>
footer.php,內容:
</body> </html>
而後,在 views/item 建立如下幾個視圖文件。
index.php,瀏覽數據庫內 item 表的全部記錄,內容:
<form action="../item/add" method="post"> <input type="text" value="I have to..." onclick="this.value=''" name="value"> <input type="submit" value="添加"> </form> <br/><br/> <?php $number = 0?> <?php foreach ($todo as $todoitem):?> <a class="big" href="../../item/view/<?php%20echo%20$todoitem['Item']['id']?>/<?php%20echo%20strtolower(str_replace(" ","-",$todoitem['Item']['item_name']))?>"> <span class="item"> <?php echo ++$number?> <?php echo $todoitem['Item']['item_name']?> </span> </a> ---- <a class="big" href="../item/delete/<?php%20echo%20$todoitem['Item']['id']?>">刪除</a> <br/> <?php endforeach?>
add.php,添加記錄,內容:
<a class="big" href="../item/">添加成功,點擊返回</a>
view.php,查看單條記錄,內容:
<form action="../../../item/update" method="post"> <input type="text" value="<?php echo $todo['Item']['item_name'] ?>" name="value"> <input type="hidden" value="<?php echo $todo['Item']['id'] ?>" name="id"> <input type="submit" value="修改"> </form> <a class="big" href="../../../item/">返回</a>
update.php,更改記錄,內容:
<a class="big" href="../item/index/">修改爲功,點擊返回</a>
delete.php,刪除記錄,內容:
<a href="../../item/">刪除成功,點擊返回</a>
這樣,在瀏覽器中訪問 todo 程序:http://localhost/todo/item/index/,就能夠看到效果了。
以上代碼所有發佈到了個人 github 上,代碼倉地址:https://github.com/yeszao/FastPHP,歡迎克隆、提交。
下載: fastphp-master
原文: http://www.awaimai.com/128.html
更多參考:
PHP5: mysqli 插入, 查詢, 更新和刪除 Insert Update Delete Using mysqli (CRUD)
本文轉自: PHP: 手把手編寫本身的 MVC 框架實例教程