如何編寫PHPMVC框架

這篇文章主要介紹“如何編寫PHP MVC框架”,在日常操作中,相信很多人在如何編寫PHP MVC框架問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”如何編寫PHP MVC框架”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

為華州等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及華州網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站設(shè)計(jì)、做網(wǎng)站、華州網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!

1 什么是MVC

MVC模式(Model-View-Controller)是軟件工程中的一種軟件架構(gòu)模式。 MVC把軟件系統(tǒng)分為三個(gè)基本部分:模型(Model)、視圖(View)和控制器(Controller)。 PHP中MVC模式也稱Web MVC,從上世紀(jì)70年代進(jìn)化而來。 MVC的目的是實(shí)現(xiàn)一種動(dòng)態(tài)的程序設(shè)計(jì),便于后續(xù)對(duì)程序的修改和擴(kuò)展簡化,并且使程序某一部分的重復(fù)利用成為可能。 除此之外,此模式通過對(duì)復(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)給用戶。

如何編寫PHP MVC框架

一個(gè)典型的Web MVC流程:

1、Controller截獲用戶發(fā)出的請求;

2、Controller調(diào)用Model完成狀態(tài)的讀寫操作;

3、Controller把數(shù)據(jù)傳遞給View;

4、View渲染最終結(jié)果并呈獻(xiàn)給用戶。

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

網(wǎng)絡(luò)上有大量優(yōu)秀的MVC框架可供使用,本教程并不是為了開發(fā)一個(gè)全面的、終極的MVC框架解決方案。 我們將它看作是一個(gè)很好的從內(nèi)部學(xué)習(xí)PHP的機(jī)會(huì)。 在此過程中,你將學(xué)習(xí)面向?qū)ο缶幊?/strong>和MVC設(shè)計(jì)模式,并學(xué)習(xí)到開發(fā)中的一些注意事項(xiàng)。 更重要的是,通過自制MVC框架,每個(gè)人都可以完全控制自己的框架,將你的想法融入到你的框架中。 這不是很美妙的事情嗎~~~

3 準(zhǔn)備工作

3.1 環(huán)境準(zhǔn)備

這里我們需要最基本的PHP環(huán)境:

  • Nginx或Apache

  • PHP5.4+

  • MySQL

推薦使用phpStudy或docker一鍵安裝這樣的LNMP環(huán)境。

3.2 代碼規(guī)范

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

1、MySQL的表名需小寫小寫加下劃線,如:item,car_orders。

2、模塊名(Models)需用大駝峰命名法,即首字母大寫,并在名稱后添加Model,如:ItemModelCarModel。

3、控制器(Controllers)需用大駝峰命名法,即首字母大寫,并在名稱后添加Controller,如:ItemController,CarController。

4、方法名(Action)需用小駝峰命名法,即首字母小寫,如:index,indexPost。

5、視圖(Views)部署結(jié)構(gòu)為控制器名/行為名,如:item/view.phpcar/buy.php。

上述規(guī)則是為了程序能更好地相互調(diào)用。 接下來就開始真正的PHP MVC編程了。

3.3 目錄準(zhǔn)備

在開始開發(fā)前,我們給這個(gè)框架先起個(gè)名字吧,就叫:Fastphp框架。 然后根據(jù)需要來把項(xiàng)目的目錄創(chuàng)建。 假設(shè)我們建立的項(xiàng)目為 project,目錄結(jié)構(gòu)就這樣:

project                 WEB部署根目錄
├─app                   應(yīng)用目錄
│  ├─controllers        控制器目錄
│  ├─models             模塊目錄
│  ├─views              視圖目錄
├─config                配置文件目錄
├─fastphp               框架核心目錄
│ ├─base                MVC基類目錄
│ ├─db                  數(shù)據(jù)庫操作類目錄
│ ├─Fastphp.php         內(nèi)核文件  
├─static                靜態(tài)文件目錄
├─index.php             入口文件

然后按照下一步,把Nginx或者Apache的站點(diǎn)根目錄配置到project目錄,。

3.4 重定向

重定向的目的有兩個(gè):設(shè)置根目錄為project所在位置,以及將所有請求都發(fā)送給 index.php 文件。 如果是Apache服務(wù)器,在 project 目錄下新建一個(gè) .htaccess文件,內(nèi)容為:

<IfModule mod_rewrite.c>
# 打開Rerite功能
RewriteEngine On

    # 如果請求的是真實(shí)存在的文件或目錄,直接訪問
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

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

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

<span class="hljs-title">location</span> / {
<span class="hljs-comment">    # 重新向所有非真是存在的請求到index.php
</span><span class="hljs-title">    try_files</span> <span class="hljs-variable">$uri</span> <span class="hljs-variable">$uri</span>/ /index.php<span class="hljs-variable">$args</span>;
}

這樣做的主要原因是:

(1)靜態(tài)文件能直接訪問。如果文件或者目錄真實(shí)存在,則直接訪問存在的文件/目錄。 比如,靜態(tài)文件static/css/main.css真實(shí)存在,就可以直接訪問它。 (2)程序有單一的入口。 這種情況是請求地址不是真實(shí)存在的文件或目錄,這樣請求就會(huì)傳到 index.php上。 例如,訪問地址:localhost/item/detail/1,在文件系統(tǒng)中并不存在這樣的文件或目錄。 那么,Apache或Nginx服務(wù)器會(huì)把請求發(fā)給index.php,并且把域名之后的字符串賦值給REQUEST_URI變量。 這樣在PHP中用$_SERVER['REQUEST_URI']就能拿到/item/detail/1; (3)可以用來生成美化的URL,利于SEO

4 PHP MVC核心文件

4.1 入口文件

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

<?php
// 應(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');

// 實(shí)例化框架類
(new fastphp\Fastphp($config))->run();

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

這么做的主要原因是:

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

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

4.2 配置文件

在入口文件中,我們加載了config.php文件的內(nèi)容,那它有何作用呢? 從名稱不難看出,它的作用是保存一些常用配置。 config.php文件內(nèi)容如下,作用是定義數(shù)據(jù)庫連接參數(shù)參數(shù),以及配置默認(rèn)控制器名和操作名:

<?php

// 數(shù)據(jù)庫配置
$config['db']['host'] = 'localhost';
$config['db']['username'] = 'root';
$config['db']['password'] = '123456';
$config['db']['dbname'] = 'project';

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

return $config;

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

4.3 框架核心類

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

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

run()方法則調(diào)用用類自身方法,完成下面幾個(gè)操作:

  • 類自動(dòng)加載

  • 環(huán)境檢查

  • 過濾敏感字符

  • 移除全局變量的老用法

  • 路由處理

fastphp目錄下新建核心類文件,名稱Fastphp.php,代碼:

<?php
namespace fastphp;

// 框架根目錄
defined('CORE_PATH') or define('CORE_PATH', __DIR__);

/**
 * fastphp框架核心
 */
class Fastphp
{
    // 配置內(nèi)容
    protected $config = [];

    public function __construct($config)
    {
        $this->config = $config;
    }

    // 運(yùn)行程序
    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]);

            // 獲取動(dòng)作名
            array_shift($urlArray);
            $actionName = $urlArray ? $urlArray[0] : $actionName;

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

        // 判斷控制器和操作是否存在
        $controller = 'app\\controllers\\'. $controllerName . 'Controller';
        if (!class_exists($controller)) {
            exit($controller . '控制器不存在');
        }
        if (!method_exists($controller, $actionName)) {
            exit($actionName . '方法不存在');
        }

        // 如果控制器和操作名存在,則實(shí)例化控制器,因?yàn)榭刂破鲗?duì)象里面
        // 還會(huì)用到控制器名和操作名,所以實(shí)例化的時(shí)候把他們倆的名稱也
        // 傳進(jìn)去。結(jié)合Controller基類一起看
        $dispatch = new $controller($controllerName, $actionName);

        // $dispatch保存控制器實(shí)例化后的對(duì)象,我們就可以調(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) : '';
        }
    }

    // 檢測自定義全局變量并移除。因?yàn)?nbsp;register_globals 已經(jīng)棄用,如果
    // 已經(jīng)棄用的 register_globals 指令被設(shè)置為 on,那么局部變量也將
    // 在腳本的全局作用域中可用。 例如, $_POST['foo'] 也將以 $foo 的
    // 形式存在,這樣寫是不好的實(shí)現(xiàn),會(huì)影響代碼中的其他變量。 相關(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']) {
            define('DB_HOST', $this->config['db']['host']);
            define('DB_NAME', $this->config['db']['dbname']);
            define('DB_USER', $this->config['db']['username']);
            define('DB_PASS', $this->config['db']['password']);
        }
    }

    // 自動(dòng)加載類
    public function loadClass($className)
    {
        $classMap = $this->classMap();

        if (isset($classMap[$className])) {
            // 包含內(nèi)核文件
            $file = $classMap[$className];
        } elseif (strpos($className, '\\') !== false) {
            // 包含應(yīng)用(application目錄)文件
            $file = APP_PATH . str_replace('\\', '/', $className) . '.php';
            if (!is_file($file)) {
                return;
            }
        } else {
            return;
        }

        include $file;

        // 這里可以加入判斷,如果名為$className的類、接口或者性狀不存在,則在調(diào)試模式下拋出錯(cuò)誤
    }

    // 內(nèi)核文件命名空間映射關(guān)系
    protected function classMap()
    {
        return [
            'fastphp\base\Controller' => CORE_PATH . '/base/Controller.php',
            'fastphp\base\Model' => CORE_PATH . '/base/Model.php',
            'fastphp\base\View' => CORE_PATH . '/base/View.php',
            'fastphp\db\Db' => CORE_PATH . '/db/Db.php',
            'fastphp\db\Sql' => CORE_PATH . '/db/Sql.php',
        ];
    }
}

下面重點(diǎn)講解主請求方法 route(),它也稱路由方法。 路由方法的主要作用是:截取URL,并解析出控制器名、方法名和URL參數(shù)。 假設(shè)我們的 URL 是這樣:

yoursite.com/controllerName/actionName/queryString

當(dāng)瀏覽器訪問上面的URL,route()從全局變量 $_SERVER['REQUEST_URI']中獲取到字符串/controllerName/actionName/queryString。 然后,會(huì)將這個(gè)字符串分割成三部分:controllerName、actionNamequeryString。 例如,URL鏈接為:yoursite.com/item/detail/1/hello,那么route()分割之后,

  • ControllerName名就是:item

  • actionName名就是:detail

  • URL參數(shù)就是:array(1, hello)

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

4.4 Controller基類

接下來,就是在 fastphp中創(chuàng)建MVC基類,包括控制器、模型視圖三個(gè)基類。 在fastphp/base/目錄下新建控制器基類,文件名 Controller.php,功能就是總調(diào)度,內(nèi)容如下:

<?php
namespace fastphp\base;

/**
 * 控制器基類
 */
class Controller
{
    protected $_controller;
    protected $_action;
    protected $_view;

    // 構(gòu)造函數(shù),初始化屬性,并實(shí)例化對(duì)應(yīng)模型
    public function __construct($controller, $action)
    {
        $this->_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()方法實(shí)現(xiàn)把變量保存到View對(duì)象中。 這樣,在調(diào)用$this->render() 后視圖文件就能顯示這些變量。

4.5 Model基類

新建模型基類,繼承自數(shù)據(jù)庫操作類Sql類。 因?yàn)閿?shù)據(jù)庫操作比較復(fù)雜,所以SQL操作我們單獨(dú)創(chuàng)建一個(gè)類。 Model基類涉及到3個(gè)類:Model基類本身,它的父類SQL,以及提供數(shù)據(jù)庫連接句柄的Db類。 在fastphp/base/目錄下新建模型基類文件,名為 Model.php,代碼如下:

<?php
namespace fastphp\base;

use fastphp\db\Sql;

class Model extends Sql
{
    protected $model;

    public function __construct()
    {
        // 獲取數(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);
        }
    }
}

fastphp/db/目錄下建立一個(gè)數(shù)據(jù)庫基類 Sql.php,代碼如下:

<?php
namespace fastphp\db;

use \PDOStatement;

class Sql
{
    // 數(shù)據(jù)庫表名
    protected $table;

    // 數(shù)據(jù)庫主鍵
    protected $primary = 'id';

    // WHERE和ORDER拼裝后的條件
    private $filter = '';

    // Pdo bindParam()綁定的參數(shù)集合
    private $param = array();

    /**
     * 查詢條件拼接,使用方式:
     *
     * $this->where(['id = 1','and title=Web', ...])->fetch();
     * 為防止注入,建議通過$param方式傳入?yún)?shù):
     * $this->where(['id = :id'], [':id' => $id])->fetch();
     *
     * @param array $where 條件
     * @return $this 當(dāng)前對(duì)象
     */
    public function where($where = array(), $param = array())
    {
        if ($where) {
            $this->filter .= ' WHERE ';
            $this->filter .= implode(' ', $where);

            $this->param = $param;
        }

        return $this;
    }

    /**
     * 拼裝排序條件,使用方式:
     *
     * $this->order(['id DESC', 'title ASC', ...])->fetch();
     *
     * @param array $order 排序條件
     * @return $this
     */
    public function order($order = array())
    {
        if($order) {
            $this->filter .= ' ORDER BY ';
            $this->filter .= implode(',', $order);
        }

        return $this;
    }

    // 查詢所有
    public function fetchAll()
    {
        $sql = sprintf(select * from `%s` %s, $this->table, $this->filter);
        $sth = Db::pdo()->prepare($sql);
        $sth = $this->formatParam($sth, $this->param);
        $sth->execute();

        return $sth->fetchAll();
    }

    // 查詢一條
    public function fetch()
    {
        $sql = sprintf(select * from `%s` %s, $this->table, $this->filter);
        $sth = Db::pdo()->prepare($sql);
        $sth = $this->formatParam($sth, $this->param);
        $sth->execute();

        return $sth->fetch();
    }

    // 根據(jù)條件 (id) 刪除
    public function delete($id)
    {
        $sql = sprintf(delete from `%s` where `%s` = :%s, $this->table, $this->primary, $this->primary);
        $sth = Db::pdo()->prepare($sql);
        $sth = $this->formatParam($sth, [$this->primary => $id]);
        $sth->execute();

        return $sth->rowCount();
    }

    // 新增數(shù)據(jù)
    public function add($data)
    {
        $sql = sprintf(insert into `%s` %s, $this->table, $this->formatInsert($data));
        $sth = Db::pdo()->prepare($sql);
        $sth = $this->formatParam($sth, $data);
        $sth = $this->formatParam($sth, $this->param);
        $sth->execute();

        return $sth->rowCount();
    }

    // 修改數(shù)據(jù)
    public function update($data)
    {
        $sql = sprintf(update `%s` set %s %s, $this->table, $this->formatUpdate($data), $this->filter);
        $sth = Db::pdo()->prepare($sql);
        $sth = $this->formatParam($sth, $data);
        $sth = $this->formatParam($sth, $this->param);
        $sth->execute();

        return $sth->rowCount();
    }

    /**
     * 占位符綁定具體的變量值
     * @param PDOStatement $sth 要綁定的PDOStatement對(duì)象
     * @param array $params 參數(shù),有三種類型:
     * 1)如果SQL語句用問號(hào)?占位符,那么$params應(yīng)該為
     *    [$a, $b, $c]
     * 2)如果SQL語句用冒號(hào):占位符,那么$params應(yīng)該為
     *    ['a' => $a, 'b' => $b, 'c' => $c]
     *    或者
     *    [':a' => $a, ':b' => $b, ':c' => $c]
     *
     * @return PDOStatement
     */
    public function formatParam(PDOStatement $sth, $params = array())
    {
        foreach ($params as $param => &$value) {
            $param = is_int($param) ? $param + 1 : ':' . ltrim($param, ':');
            $sth->bindParam($param, $value);
        }

        return $sth;
    }

    // 將數(shù)組轉(zhuǎn)換成插入格式的sql語句
    private function formatInsert($data)
    {
        $fields = array();
        $names = array();
        foreach ($data as $key => $value) {
            $fields[] = sprintf(`%s`, $key);
            $names[] = sprintf(:%s, $key);
        }

        $field = implode(',', $fields);
        $name = implode(',', $names);

        return sprintf((%s) values (%s), $field, $name);
    }

    // 將數(shù)組轉(zhuǎn)換成更新格式的sql語句
    private function formatUpdate($data)
    {
        $fields = array();
        foreach ($data as $key => $value) {
            $fields[] = sprintf(`%s` = :%s, $key, $key);
        }

        return implode(',', $fields);
    }
}

應(yīng)該說,Sql基類是框架的核心部分。為什么? 因?yàn)橥ㄟ^它,我們創(chuàng)建了一個(gè) SQL 抽象層,可以大大減少了數(shù)據(jù)庫的編程工作。 雖然 PDO 接口本來已經(jīng)很簡潔,但是抽象之后框架的可靈活性更高。 Sql類里面有用到Db:pdo()方法,這是我們創(chuàng)建的Db類,它提供一個(gè)PDO單例。 在fastphp/db/目錄下創(chuàng)建Db.php文件,內(nèi)容:

<?php
namespace fastphp\db;

use PDO;
use PDOException;

/**
 * 數(shù)據(jù)庫操作類。
 * 其$pdo屬性為靜態(tài)屬性,所以在頁面執(zhí)行周期內(nèi),
 * 只要一次賦值,以后的獲取還是首次賦值的內(nèi)容。
 * 這里就是PDO對(duì)象,這樣可以確保運(yùn)行期間只有一個(gè)
 * 數(shù)據(jù)庫連接對(duì)象,這是一種簡單的單例模式
 * Class Db
 */
class Db
{
    private static $pdo = null;

    public static function pdo()
    {
        if (self::$pdo !== null) {
            return self::$pdo;
        }

        try {
            $dsn    = sprintf('mysql:host=%s;dbname=%s;charset=utf8', DB_HOST, DB_NAME);
            $option = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

            return self::$pdo = new PDO($dsn, DB_USER, DB_PASS, $option);
        } catch (PDOException $e) {
            exit($e->getMessage());
        }
    }
}

4.6 View基類

fastphp/base/目錄下新建視圖基類 View.php內(nèi)容如下:

<?php
namespace fastphp\base;

/**
 * 視圖基類
 */
class View
{
    protected $variables = array();
    protected $_controller;
    protected $_action;

    function __construct($controller, $action)
    {
        $this->_controller = strtolower($controller);
        $this->_action = strtolower($action);
    }

    // 分配變量
    public function assign($name, $value)
    {
        $this->variables[$name] = $value;
    }

    // 渲染顯示
    public function render()
    {
        extract($this->variables);
        $defaultHeader = APP_PATH . 'app/views/header.php';
        $defaultFooter = APP_PATH . 'app/views/footer.php';

        $controllerHeader = APP_PATH . 'app/views/' . $this->_controller . '/header.php';
        $controllerFooter = APP_PATH . 'app/views/' . $this->_controller . '/footer.php';
        $controllerLayout = APP_PATH . 'app/views/' . $this->_controller . '/' . $this->_action . '.php';

        // 頁頭文件
        if (is_file($controllerHeader)) {
            include ($controllerHeader);
        } else {
            include ($defaultHeader);
        }

        //判斷視圖文件是否存在
        if (is_file($controllerLayout)) {
            include ($controllerLayout);
        } else {
            echo <h2>無法找到視圖文件</h2>;
        }

        // 頁腳文件
        if (is_file($controllerFooter)) {
            include ($controllerFooter);
        } else {
            include ($defaultFooter);
        }
    }
}

這樣,核心的PHP MVC框架核心就完成了。 下面我們編寫應(yīng)用來測試框架功能。

5 應(yīng)用

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

在 SQL 中新建一個(gè) project數(shù)據(jù)庫,增加一個(gè)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!');

5.2 部署模型

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

<?php
namespace app\models;

use fastphp\base\Model;
use fastphp\db\Db;

/**
 * 用戶Model
 */
class ItemModel extends Model
{
    /**
     * 自定義當(dāng)前模型操作的數(shù)據(jù)庫表名稱,
     * 如果不指定,默認(rèn)為類名稱的小寫字符串,
     * 這里就是 item 表
     * @var string
     */
    protected $table = 'item';

    /**
     * 搜索功能,因?yàn)镾ql父類里面沒有現(xiàn)成的like搜索,
     * 所以需要自己寫SQL語句,對(duì)數(shù)據(jù)庫的操作應(yīng)該都放
     * 在Model里面,然后提供給Controller直接調(diào)用
     * @param $title string 查詢的關(guān)鍵詞
     * @return array 返回的數(shù)據(jù)
     */
    public function search($keyword)
    {
        $sql = select * from `$this->table` where `item_name` like :keyword;
        $sth = Db::pdo()->prepare($sql);
        $sth = $this->formatParam($sth, [':keyword' => %$keyword%]);
        $sth->execute();

        return $sth->fetchAll();
    }
}

因?yàn)?Item 模型繼承了 Model基類,所以它擁有 Model 類的所有功能。

5.3 部署控制器

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

<?php
namespace app\controllers;

use fastphp\base\Controller;
use app\models\ItemModel;

class ItemController extends Controller
{
    // 首頁方法,測試框架自定義DB查詢
    public function index()
    {
        $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';

        if ($keyword) {
            $items = (new ItemModel())->search($keyword);
        } else {
            // 查詢所有內(nèi)容,并按倒序排列輸出
            // where()方法可不傳入?yún)?shù),或者省略
            $items = (new ItemModel)->where()->order(['id DESC'])->fetchAll();
        }

        $this->assign('title', '全部條目');
        $this->assign('keyword', $keyword);
        $this->assign('items', $items);
        $this->render();
    }

    // 查看單條記錄詳情
    public function detail($id)
    {
        // 通過?占位符傳入$id參數(shù)
        $item = (new ItemModel())->where([id = ?], [$id])->fetch();

        $this->assign('title', '條目詳情');
        $this->assign('item', $item);
        $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();
    }

    // 操作管理
    public function manage($id = 0)
    {
        $item = array();
        if ($id) {
            // 通過名稱占位符傳入?yún)?shù)
            $item = (new ItemModel())->where([id = :id], [':id' => $id])->fetch();
        }

        $this->assign('title', '管理?xiàng)l目');
        $this->assign('item', $item);
        $this->render();
    }

    // 更新記錄,測試框架DB記錄更新(Update)
    public function update()
    {
        $data = array('id' => $_POST['id'], 'item_name' => $_POST['value']);
        $count = (new ItemModel)->where(['id = :id'], [':id' => $data['id']])->update($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();
    }
}

5.4 部署視圖

app/views/目錄下新建 header.php 和 footer.php 兩個(gè)頁頭頁腳模板,如下。 header.php內(nèi)容:

<html>
<head>
    <meta http-equiv=Content-Type content=text/html; charset=utf-8 />
    <title><?php echo $title ?></title>
    <link rel=stylesheet href=/static/css/main.css type=text/css />
</head>
<body>
    <h2><?php echo $title ?></h2>

footer.php內(nèi)容:

</body>
</html>

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

html, body {
margin: 0;
padding: 10px;
font-size: 20px;
}

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

a {
color:blue;
font-family:georgia,times;
line-height:1.2em;
text-decoration:none;
}

a:hover {
text-decoration:underline;
}

h2 {
color:#000000;
font-size:41px;
border-bottom:1px dotted #cccccc;
}

td {padding: 1px 30px 1px 0;}

然后,在 app/views/item 目錄下創(chuàng)建以下幾個(gè)視圖文件。 index.php,瀏覽數(shù)據(jù)庫內(nèi) item 表的所有記錄,內(nèi)容:

<form action= method=get>
    <input type=text value=<?php echo $keyword ?> name=keyword>
    <input type=submit value=搜索>
</form>

<p><a href=/item/manage>新建</a></p>

<table>
    <tr>
        <th>ID</th>
        <th>內(nèi)容</th>
        <th>操作</th>
    </tr>
    <?php foreach ($items as $item): ?>
        <tr>
            <td><?php echo $item['id'] ?></td>
            <td><?php echo $item['item_name'] ?></td>
            <td>
                <a href=/item/manage/<?php echo $item['id'] ?>>編輯</a>
                <a href=/item/delete/<?php echo $item['id'] ?>>刪除</a>
            </td>
        </tr>
    <?php endforeach ?>
</table>

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

<a class=big href=/item/index>成功添加<?php echo $count ?>條記錄,點(diǎn)擊返回</a>

manage.php,管理記錄,內(nèi)容:

<form action=<?php echo $postUrl; ?> method=post>
    <?php if (isset($item['id'])): ?>
        <input type=hidden name=id value=<?php echo $item['id'] ?>>
    <?php endif; ?>
    <input type=text name=value value=<?php echo isset($item['item_name']) ? $item['item_name'] : '' ?>>
    <input type=submit value=提交>
</form>

<a class=big href=/item/index>返回</a>

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

<a class=big href=/item/index>成功修改<?php echo $count ?>項(xiàng),點(diǎn)擊返回</a>

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

<a href=/item/index>成功刪除<?php echo $count ?>項(xiàng),點(diǎn)擊返回</a>

6 應(yīng)用測試

這樣,在瀏覽器中訪問 project程序:http://localhost/item/index/,就可以看到效果了。
如何編寫PHP MVC框架

到此,關(guān)于“如何編寫PHP MVC框架”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

分享文章:如何編寫PHPMVC框架
鏈接分享:http://www.muchs.cn/article48/ijcihp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)、商城網(wǎng)站、App設(shè)計(jì)建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司

網(wǎng)站設(shè)計(jì)公司知識(shí)