PHP入門教程之編寫自己的PHP框架

1 什么是MVC

MVC模式(Model-View-Controller)是軟件工程中的一種軟件架構(gòu)模式。

MVC把軟件系統(tǒng)分為三個基本部分:模型(Model)、視圖(View)和控制器(Controller)。

PHP中MVC模式也稱Web MVC,從上世紀(jì)70年代進(jìn)化而來。

MVC的目的是實現(xiàn)一種動態(tài)的程序設(shè)計,便于后續(xù)對程序的修改和擴(kuò)展簡化,并且使程序某一部分的重復(fù)利用成為可能。

除此之外,此模式通過對復(fù)雜度的簡化,使程序結(jié)構(gòu)更加直觀。

MVC各部分的職能:

模型Model – 管理大部分的業(yè)務(wù)邏輯和所有的數(shù)據(jù)庫邏輯。模型提供了連接和操作數(shù)據(jù)庫的抽象層。控制器Controller - 負(fù)責(zé)響應(yīng)用戶請求、準(zhǔn)備數(shù)據(jù),以及決定如何展示數(shù)據(jù)。視圖View – 負(fù)責(zé)渲染數(shù)據(jù),通過HTML方式呈現(xiàn)給用戶。

一個典型的Web MVC流程:

Controller截獲用戶發(fā)出的請求;Controller調(diào)用Model完成狀態(tài)的讀寫操作;Controller把數(shù)據(jù)傳遞給View;View渲染最終結(jié)果并呈獻(xiàn)給用戶。

2 為什么要自己開發(fā)MVC框架

網(wǎng)絡(luò)上有大量優(yōu)秀的MVC框架可供使用,本教程并不是為了開發(fā)一個全面的、終極的MVC框架解決方案。

我們將它看作是一個很好的從內(nèi)部學(xué)習(xí)PHP的機(jī)會。

在此過程中,你將學(xué)習(xí)面向?qū)ο缶幊毯蚆VC設(shè)計模式,并學(xué)習(xí)到開發(fā)中的一些注意事項。

更重要的是,通過自制MVC框架,每個人都可以完全控制自己的框架,將你的想法融入到你開發(fā)的框架中。

雖然不一定是最好的,但是你可以按照自己的方式開發(fā)各種功能。

3 開始開發(fā)自己的MVC框架

3.1 目錄準(zhǔn)備

在開始開發(fā)前,讓我們先來把項目建立好。

假設(shè)我們建立的項目為 project,MVC的框架命名為 fastphp,那么接下來,第一步要把目錄結(jié)構(gòu)設(shè)置好。

project

WEB部署目錄 ├─application 應(yīng)用目錄 │ ├─controllers 控制器目錄 │ ├─models 模塊目錄 │

├─views 視圖目錄 ├─config 配置文件目錄 ├─fastphp 框架核心目錄 ├─static 靜態(tài)文件目錄

├─index.php 入口文件

然后把Nginx或者Apache的站點根目錄配置到project目錄。

3.2 代碼規(guī)范

在目錄設(shè)置好以后,我們接下來規(guī)定代碼的規(guī)范:

MySQL的表名需小寫或小寫加下劃線,如:item,car_orders。模塊名(Models)需用大駝峰命名法,即首字母大寫,并在名稱后添加Model,如:ItemModel,CarModel。控制器(Controllers)需用大駝峰命名法,即首字母大寫,并在名稱后添加Controller,如:ItemController,CarController。方法名(Action)需用小駝峰命名法,即首字母小寫,如:index,indexPost。視圖(Views)部署結(jié)構(gòu)為控制器名/行為名,如:item/view.php,car/buy.php。

上述規(guī)則是為了程序能更好地相互調(diào)用。

接下來就開始真正的PHP MVC編程了。

3.3 重定向

重定向的目的有兩個:設(shè)置根目錄為project所在位置,以及將所有請求都發(fā)送給 index.php 文件。

如果是Apache服務(wù)器,在 project 目錄下新建一個 .htaccess 文件,內(nèi)容為:

mod_rewrite.c> # 打開Rerite功能 RewriteEngine On # 如果請求的是真實存在的文件或目錄,直接訪問

RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d

# 如果訪問的文件或目錄不是真事存在,分發(fā)請求至 index.php RewriteRule .

index.php

如果是Nginx服務(wù)器,修改配置文件,在server塊中加入如下的重定向:

location / { # 重新向所有非真是存在的請求到index.php try_files $uri $uri/ /index.php$args; }

這樣做的主要原因是:

(1)靜態(tài)文件能直接訪問。

如果文件或者目錄真實存在,則直接訪問存在的文件/目錄。

比如,靜態(tài)文件static/css/main.css真實存在,就可以直接訪問它。

(2)程序有單一的入口。

這種情況是請求地址不是真實存在的文件或目錄,這樣請求就會傳到 index.php 上。

例如,訪問地址:localhost/item/view/1,在文件系統(tǒng)中并不存在這樣的文件或目錄。

那么,Apache或Nginx服務(wù)器會把請求發(fā)給index.php,并且把域名之后的字符串賦值給REQUEST_URI變量。

這樣在PHP中用$_SERVER['REQUEST_URI']就能拿到/item/view/1;

(3)可以用來生成美化的URL,利于SEO。

3.4 入口文件

接下來,在 project 目錄下新建 index.php 入口文件,文件內(nèi)容為:


應(yīng)用目錄為當(dāng)前目錄define('APP_PATH', __DIR__ . '/');// 開啟調(diào)試模式define('APP_DEBUG',

true);// 加載框架文件require(APP_PATH . 'fastphp/Fastphp.php');//

加載配置文件$config = require(APP_PATH . 'config/config.php');// 實例化框架類(new

Fastphp($config))->run();

注意,上面的PHP代碼中,并沒有添加PHP結(jié)束符號?>。

這么做的主要原因是:

對于只有 PHP 代碼的文件,最好沒有結(jié)束標(biāo)志?>,

PHP自身并不需要結(jié)束符號,不加結(jié)束符讓程序更加安全,很大程度防止了末尾被注入額外的內(nèi)容。

3.5 配置文件

在入口文件中,我們加載了config.php文件的內(nèi)容,那它有何作用呢?

從名稱不難看出,它的作用是保存一些常用配置。

config.php 文件內(nèi)容如下,作用是定義數(shù)據(jù)庫連接參數(shù)參數(shù),以及配置默認(rèn)控制器名和操作名:


數(shù)據(jù)庫配置define('DB_NAME', 'project'); define('DB_USER', 'root');

define('DB_PASSWORD', '123456'); define('DB_HOST', 'localhost');//

默認(rèn)控制器和操作名$config['defaultController'] = 'Item'; $config['defaultAction']

= 'index';return $config;

入口中的$config變量接收到配置參數(shù)后,再傳給框架的核心類,也就是Fastphp類。

3.6 框架核心類

入口文件對框架類做了兩步操作:實例化,調(diào)用run()方法。

實例化操作接受$config參數(shù)配置,并保存到類屬性中。

run()方法則調(diào)用用類自身方法,完成:自動加載類文件、監(jiān)測開發(fā)環(huán)境、過濾敏感字符、移除全局變量的老用法、和處理路由。


* fastphp框架核心 */class Fastphp{ protected $_config = []; public function

__construct($config) { $this->_config = $config; } // 運行程序 public

function run() { spl_autoload_register(array($this, 'loadClass'));

$this->setReporting(); $this->removeMagicQuotes();

$this->unregisterGlobals(); $this->setDbConfig();

$this->route(); } // 路由處理 public function route() { $controllerName =

$this->_config['defaultController']; $actionName =

$this->_config['defaultAction']; $param = array(); $url =

$_SERVER['REQUEST_URI']; // 清除?之后的內(nèi)容 $position = strpos($url, '?'); $url

= $position === false ? $url : substr($url, 0, $position); // 刪除前后的“/”

$url = trim($url, '/'); if ($url) { // 使用“/”分割字符串,并保存在數(shù)組中 $urlArray =

explode('/', $url); // 刪除空的數(shù)組元素 $urlArray = array_filter($urlArray); //

獲取控制器名 $controllerName = ucfirst($urlArray[0]); // 獲取動作名

array_shift($urlArray); $actionName = $urlArray ? $urlArray[0] :

$actionName; // 獲取URL參數(shù) array_shift($urlArray); $param = $urlArray ?

$urlArray : array(); } // 判斷控制器和操作是否存在 $controller = $controllerName .

'Controller'; if (!class_exists($controller)) { exit($controller .

'控制器不存在'); } if (!method_exists($controller, $actionName)) {

exit($actionName . '方法不存在'); } // 如果控制器和操作名存在,則實例化控制器,因為控制器對象里面 //

還會用到控制器名和操作名,所以實例化的時候把他們倆的名稱也 // 傳進(jìn)去。結(jié)合Controller基類一起看 $dispatch = new

$controller($controllerName, $actionName); //

$dispatch保存控制器實例化后的對象,我們就可以調(diào)用它的方法, //

也可以像方法中傳入?yún)?shù),以下等同于:$dispatch->$actionName($param)

call_user_func_array(array($dispatch, $actionName), $param); } // 檢測開發(fā)環(huán)境

public 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'); } } // 刪除敏感字符 public function

stripSlashesDeep($value) { $value = is_array($value) ?

array_map(array($this, 'stripSlashesDeep'), $value) :

stripslashes($value); return $value; } // 檢測敏感字符并刪除 public function

removeMagicQuotes() { if (get_magic_quotes_gpc()) { $_GET = isset($_GET)

? $this->stripSlashesDeep($_GET ) : ''; $_POST = isset($_POST) ?

$this->stripSlashesDeep($_POST ) : ''; $_COOKIE = isset($_COOKIE) ?

$this->stripSlashesDeep($_COOKIE) : ''; $_SESSION = isset($_SESSION) ?

$this->stripSlashesDeep($_SESSION) : ''; } } // 檢測自定義全局變量并移除。因為

register_globals 已經(jīng)棄用,如果 // 已經(jīng)棄用的 register_globals 指令被設(shè)置為 on,那么局部變量也將 //

在腳本的全局作用域中可用。 例如, $_POST['foo'] 也將以 $foo 的 //

形式存在,這樣寫是不好的實現(xiàn),會影響代碼中的其他變量。 相關(guān)信息, // 參考:

http://php.net/manual/zh/faq.using.php#faq.register-globals public

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]); } } } } } // 配置數(shù)據(jù)庫信息 public function

setDbConfig() { if ($this->_config['db']) { Model::$dbConfig =

$this->_config['db']; } } // 自動加載控制器和模型類 public static function

loadClass($class) { $frameworks = __DIR__ . '/' . $class . '.php';

$controllers = APP_PATH . 'application/controllers/' . $class . '.php';

$models = APP_PATH . 'application/models/' . $class . '.php'; if

(file_exists($frameworks)) { // 加載框架核心類 include $frameworks; } elseif

(file_exists($controllers)) { // 加載應(yīng)用控制器類 include $controllers; } elseif

(file_exists($models)) { //加載應(yīng)用模型類 include $models; } else { // 錯誤代碼 } }

}

下面重點講解主請求方法 route(),它也稱路由方法,作用是:截取URL,并解析出控制器名、方法名和URL參數(shù)。

假設(shè)我們的 URL 是這樣:

yoursite.com/controllerName/actionName/queryString

當(dāng)瀏覽器訪問上面的URL,route()從全局變量 $_SERVER['REQUEST_URI']中獲取到字符串/controllerName/actionName/queryString。

然后,會將這個字符串分割成三部分:controller、action 和 queryString。

例如,URL鏈接為:yoursite.com/item/view/1/hello,那么route()分割之后,

Controller名就是:itemaction名就是:viewURL參數(shù)就是:array(1, hello)

分割完成后,再實例化控制器:itemController,并調(diào)用其中的view方法 。

3.7 Controller基類

接下來,就是在 fastphp 中創(chuàng)建MVC基類,包括控制器、模型和視圖三個基類。

新建控制器基類,文件名 Controller.class.php,功能就是總調(diào)度,內(nèi)容如下:

_controller = $controller; $this->_action = $action; $this->_view = new View($controller, $action); } // 分配變量 public function assign($name, $value) { $this->_view->assign($name, $value); } // 渲染視圖 public function render() { $this->_view->render(); } }

Controller 類用assign()方法實現(xiàn)把變量保存到View對象中。

這樣,在調(diào)用$this-> render() 后視圖文件就能顯示這些變量。

3.8 Model基類

新建模型基類,繼承自數(shù)據(jù)庫操作類Sql類(因為數(shù)據(jù)庫操作比較復(fù)雜)。

模型基類文件名為 Model.class.php,代碼如下:


Model extends Sql{ protected $_model; protected $_table; public static

$dbConfig = []; public function __construct() { // 連接數(shù)據(jù)庫

$this->connect(self::$dbConfig['host'], self::$dbConfig['username'],

self::$dbConfig['password'], self::$dbConfig['dbname']); // 獲取數(shù)據(jù)庫表名 if

(!$this->_table) { // 獲取模型類名稱 $this->_model = get_class($this); //

刪除類名最后的 Model 字符 $this->_model = substr($this->_model, 0, -5); //

數(shù)據(jù)庫表名與類名一致 $this->_table = strtolower($this->_model); } } }

建立一個數(shù)據(jù)庫基類 Sql.class.php,代碼如下:

PDO::FETCH_ASSOC); $this->_dbHandle = new PDO($dsn, $username, $password, $option); } catch (PDOException $e) { exit('錯誤: ' . $e->getMessage()); } } // 查詢條件 public function where($where = array()) { if (isset($where)) { $this->filter .= ' WHERE '; $this->filter .= implode(' ', $where); } return $this; } // 排序條件 public function order($order = array()) { if(isset($order)) { $this->filter .= ' ORDER BY '; $this->filter .= implode(',', $order); } return $this; } // 查詢所有 public function selectAll() { $sql = sprintf("select * from `%s` %s", $this->_table, $this->filter); $sth = $this->_dbHandle->prepare($sql); $sth->execute(); return $sth->fetchAll(); } // 根據(jù)條件 (id) 查詢 public function select($id) { $sql = sprintf("select * from `%s` where `id` = '%s'", $this->_table, $id); $sth = $this->_dbHandle->prepare($sql); $sth->execute(); return $sth->fetch(); } // 根據(jù)條件 (id) 刪除 public function delete($id) { $sql = sprintf("delete from `%s` where `id` = '%s'", $this->_table, $id); $sth = $this->_dbHandle->prepare($sql); $sth->execute(); return $sth->rowCount(); } // 自定義SQL查詢,返回影響的行數(shù) public function query($sql) { $sth = $this->_dbHandle->prepare($sql); $sth->execute(); return $sth->rowCount(); } // 新增數(shù)據(jù) public function add($data) { $sql = sprintf("insert into `%s` %s", $this->_table, $this->formatInsert($data)); return $this->query($sql); } // 修改數(shù)據(jù) public function update($id, $data) { $sql = sprintf("update `%s` set %s where `id` = '%s'", $this->_table, $this->formatUpdate($data), $id); return $this->query($sql); } // 將數(shù)組轉(zhuǎn)換成插入格式的sql語句 private function formatInsert($data) { $fields = array(); $values = array(); foreach ($data as $key => $value) { $fields[] = sprintf("`%s`", $key); $values[] = sprintf("'%s'", $value); } $field = implode(',', $fields); $value = implode(',', $values); return sprintf("(%s) values (%s)", $field, $value); } // 將數(shù)組轉(zhuǎn)換成更新格式的sql語句 private function formatUpdate($data) { $fields = array(); foreach ($data as $key => $value) { $fields[] = sprintf("`%s` = '%s'", $key, $value); } return implode(',', $fields); } }

應(yīng)該說,Sql.class.php 是框架的核心部分。為什么?

因為通過它,我們創(chuàng)建了一個 SQL 抽象層,可以大大減少了數(shù)據(jù)庫的編程工作。

雖然 PDO 接口本來已經(jīng)很簡潔,但是抽象之后框架的可靈活性更高。

這里的數(shù)據(jù)庫句柄$this->_dbHandle還能用單例模式返回,讓數(shù)據(jù)讀寫更高效,這部分可自行實現(xiàn)。

3.9 View基類

視圖基類 View.class.php 內(nèi)容如下:

_controller = $controller; $this->_action = $action; } // 分配變量 public function assign($name, $value) { $this->variables[$name] = $value; } // 渲染顯示 public 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'; $controllerLayout = APP_PATH . 'application/views/' . $this->_controller . '/' . $this->_action . '.php'; // 頁頭文件 if (file_exists($controllerHeader)) { include ($controllerHeader); } else { include ($defaultHeader); } include ($controllerLayout); // 頁腳文件 if (file_exists($controllerFooter)) { include ($controllerFooter); } else { include ($defaultFooter); } } }

這樣,核心的PHP MVC框架核心就完成了。

下面我們編寫應(yīng)用來測試框架功能。

4 應(yīng)用

4.1 數(shù)據(jù)庫部署

在 SQL 中新建一個 project 數(shù)據(jù)庫,增加一個item 表、并插入兩條記錄,命令如下:

CREATE

DATABASE `project` DEFAULT CHARACTER SET utf8 COLLATE

utf8_general_ci;USE `project`;CREATE TABLE `item` ( `id` int(11) NOT

NULL auto_increment, `item_name` varchar(255) NOT NULL, PRIMARY KEY

(`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; INSERT

INTO `item` VALUES(1, 'Hello World.');INSERT INTO `item` VALUES(2, 'Lets

go!');

4.2 部署模型

然后,我們還需要在 models 目錄中創(chuàng)建一個 ItemModel.php 模型,內(nèi)容如下:


* 用戶模塊,一般與數(shù)據(jù)庫表名對應(yīng) * 例如表名為:item,那么Model類名應(yīng)該為:ItemModel *

也可以添加一個$_table屬性指定表名 */class ItemModel extends Model{ public $_table =

'item'; }

因為 Item 模型繼承了 Model基類,所以它擁有 Model 類的所有功能。

4.3 部署控制器

在 controllers 目錄下創(chuàng)建一個 ItemController.php 控制器,內(nèi)容如下:

selectAll(); $this->assign('title', '全部條目'); $this->assign('items', $items); $this->render(); } // 添加記錄,測試框架DB記錄創(chuàng)建(Create) public function add() { $data['item_name'] = $_POST['value']; $count = (new ItemModel)->add($data); $this->assign('title', '添加成功'); $this->assign('count', $count); $this->render(); } // 查看記錄,測試框架DB記錄讀取(Read) public function view($id = null) { $item = (new ItemModel)->select($id); $this->assign('title', '正在查看' . $item['item_name']); $this->assign('item', $item); $this->render(); } // 更新記錄,測試框架DB記錄更新(Update) public function update() { $data = array('id' => $_POST['id'], 'item_name' => $_POST['value']); $count = (new ItemModel)->update($data['id'], $data); $this->assign('title', '修改成功'); $this->assign('count', $count); $this->render(); } // 刪除記錄,測試框架DB記錄刪除(Delete) public function delete($id = null) { $count = (new ItemModel)->delete($id); $this->assign('title', '刪除成功'); $this->assign('count', $count); $this->render(); } }

4.4 部署視圖

在 views 目錄下新建 header.php 和 footer.php 兩個頁頭頁腳模板,如下。

header.php 內(nèi)容:

/> <?php echo $title ?>

rel="stylesheet" href="/static/css/main.css" type="text/css"

/>

?>

footer.php 內(nèi)容:

頁頭文件用到了main.css樣式文件,內(nèi)容:

input

{ font-family:georgia,times; font-size:24px; line-height:1.2em; }a {

color:blue; font-family:georgia,times; font-size:20px;

line-height:1.2em; text-decoration:none; }a:hover {

text-decoration:underline; }h1 { color:#000000; font-size:41px;

border-bottom:1px dotted #cccccc; }

然后,在 views/item 創(chuàng)建以下幾個視圖文件。

index.php,瀏覽數(shù)據(jù)庫內(nèi) item 表的所有記錄,內(nèi)容:


---- 刪除

add.php,添加記錄,內(nèi)容:

成功添加條記錄,點擊返回

view.php,查看單條記錄,內(nèi)容:

" type="text"> " type="hidden"> 返回

update.php,更改記錄,內(nèi)容:

成功修改項,點擊返回

delete.php,刪除記錄,內(nèi)容:

成功刪除項,點擊返回

4.5 應(yīng)用測試

這樣,在瀏覽器中訪問 project程序:http://localhost/item/index/,就可以看到效果了。

以上代碼已經(jīng)全部發(fā)布到 github 上,關(guān)鍵部分加了注釋:

倉庫地址:https://github.com/yeszao/fastphp源碼打包:https://github.com/yeszao/fastphp/archive/master.zip

著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。互聯(lián)網(wǎng)+時代,時刻要保持學(xué)習(xí),攜手千鋒PHP,Dream It Possible。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容