国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home 類(lèi)庫(kù)下載 PHP類(lèi)庫(kù) Write the PHP framework step by step and gain an in-depth understanding of the MVC operation process

Write the PHP framework step by step and gain an in-depth understanding of the MVC operation process

Oct 09, 2016 pm 01:26 PM
php framework

1?什么是MVC

MVC模式(Model-View-Controller)是軟件工程中的一種軟件架構(gòu)模式,把軟件系統(tǒng)分為三個(gè)基本部分:模型(Model)、視圖(View)和控制器(Controller)。

PHP中MVC模式也稱(chēng)Web MVC,從上世紀(jì)70年代進(jìn)化而來(lái)。MVC的目的是實(shí)現(xiàn)一種動(dòng)態(tài)的程序設(shè)計(jì),便于后續(xù)對(duì)程序的修改和擴(kuò)展簡(jiǎn)化,并且使程序某一部分的重復(fù)利用成為可能。除 此之外,此模式通過(guò)對(duì)復(fù)雜度的簡(jiǎn)化,使程序結(jié)構(gòu)更加直觀(guān)。軟件系統(tǒng)通過(guò)對(duì)自身基本部份分離的同時(shí),也賦予了各個(gè)基本部分應(yīng)有的功能。

MVC各部分的職能:

模型Model?– 管理大部分的業(yè)務(wù)邏輯和所有的數(shù)據(jù)庫(kù)邏輯。模型提供了連接和操作數(shù)據(jù)庫(kù)的抽象層。

控制器Controller?- 負(fù)責(zé)響應(yīng)用戶(hù)請(qǐng)求、準(zhǔn)備數(shù)據(jù),以及決定如何展示數(shù)據(jù)。

視圖View?– 負(fù)責(zé)渲染數(shù)據(jù),通過(guò)HTML方式呈現(xiàn)給用戶(hù)。

Write the PHP framework step by step and gain an in-depth understanding of the MVC operation process

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

Controller截獲用戶(hù)發(fā)出的請(qǐng)求;

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

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

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

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

網(wǎng)絡(luò)上有大量?jī)?yōu)秀的MVC框架可供使用,本教程并不是為了開(kāi)發(fā)一個(gè)全面的、終極的MVC框架解決方案,而是將它看作是一個(gè)很好的從內(nèi)部學(xué)習(xí)PHP的機(jī)會(huì),在此過(guò)程中,你將學(xué)習(xí)面向?qū)ο缶幊毯蚆VC設(shè)計(jì)模式,并學(xué)習(xí)到開(kāi)發(fā)中的一些注意事項(xiàng)。

更重要的是,你可以完全控制你的框架,并將你的想法融入到你開(kāi)發(fā)的框架中。雖然不一定是做好的,但是你可以按照你的方式去開(kāi)發(fā)功能和模塊。

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

3.1 目錄準(zhǔn)備

在開(kāi)始開(kāi)發(fā)前,讓我們先來(lái)把項(xiàng)目建立好,假設(shè)我們建立的項(xiàng)目為 todo,MVC的框架可以命名為 FastPHP,那么接下來(lái)的第一步就是把目錄結(jié)構(gòu)先設(shè)置好。

Write the PHP framework step by step and gain an in-depth understanding of the MVC operation process

雖然在這個(gè)教程中不會(huì)使用到上面的所有的目錄,但是為了以后程序的可拓展性,在一開(kāi)始就把程序目錄設(shè)置好使非常必要的。下面就具體說(shuō)說(shuō)每個(gè)目錄的作用:

application?– 應(yīng)用代碼

config?– 程序配置或數(shù)據(jù)庫(kù)配置

fastphp?- 框架核心目錄

public?– 靜態(tài)文件

runtime?- 臨時(shí)數(shù)據(jù)目錄

scripts?– 命令行工具

3.2 代碼規(guī)范

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

MySQL的表名需小寫(xiě),如:item,car

模塊名(Models)需首字母大寫(xiě),,并在名稱(chēng)后添加“Model”,如:ItemModel,CarModel

控制器(Controllers)需首字母大寫(xiě),,并在名稱(chēng)中添加“Controller”,如:ItemController,CarController

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

上述的一些規(guī)則是為了能在程序中更好的進(jìn)行互相的調(diào)用。接下來(lái)就開(kāi)始真正的PHP MVC編程了。

3.3 重定向

將所有的數(shù)據(jù)請(qǐng)求都重定向 index.php 文件,在 todo 目錄下新建一個(gè)?.htaccess?文件,文件內(nèi)容為:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # 確保請(qǐng)求路徑不是一個(gè)文件名或目錄
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # 重定向所有請(qǐng)求到 index.php?url=PATHNAME
    RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>

這樣做的主要原因有:

程序有一個(gè)單一的入口;

除靜態(tài)程序,其他所有程序都重定向到 index.php 上;

可以用來(lái)生成利于SEO的URL,想要更好的配置URL,后期可能會(huì)需要URL路由,這里先不做介紹了。

3.4 入口文件

做完上面的操作,就應(yīng)該知道我們需要做什么了,沒(méi)錯(cuò)!在 public 目錄下添加 index.php 文件,文件內(nèi)容為:

<?php 

// 應(yīng)用目錄為當(dāng)前目錄
define(&#39;APP_PATH&#39;, __DIR__.&#39;/&#39;);

// 開(kāi)啟調(diào)試模式
define(&#39;APP_DEBUG&#39;, true);

// 網(wǎng)站根URL
define(&#39;APP_URL&#39;, &#39;http://localhost/fastphp&#39;);

// 加載框架
require &#39;./fastphp/FastPHP.php&#39;;

注意,上面的PHP代碼中,并沒(méi)有添加PHP結(jié)束符號(hào)”?>”,這么做的主要原因是,對(duì)于只有 PHP 代碼的文件,結(jié)束標(biāo)志(“?>”)最好不存在,PHP自身并不需要結(jié)束符號(hào),不添加結(jié)束符號(hào)可以很大程度上防止末尾被添加額外的注入內(nèi)容,讓程序更加安全。

3.5 配置文件和主請(qǐng)求

在 index.php 中,我們對(duì) fastphp 文件夾下的 FastPHP.php 發(fā)起了請(qǐng)求,那么 FastPHP.php 這個(gè)啟動(dòng)文件中到底會(huì)包含哪些內(nèi)容呢?

<?php// 初始化常量
defined(&#39;FRAME_PATH&#39;) or define(&#39;FRAME_PATH&#39;, __DIR__.&#39;/&#39;);
defined(&#39;APP_PATH&#39;) or define(&#39;APP_PATH&#39;, dirname($_SERVER[&#39;SCRIPT_FILENAME&#39;]).&#39;/&#39;);
defined(&#39;APP_DEBUG&#39;) or define(&#39;APP_DEBUG&#39;, false);
defined(&#39;CONFIG_PATH&#39;) or define(&#39;CONFIG_PATH&#39;, APP_PATH.&#39;config/&#39;);
defined(&#39;RUNTIME_PATH&#39;) or define(&#39;RUNTIME_PATH&#39;, APP_PATH.&#39;runtime/&#39;);// 包含配置文件require APP_PATH . &#39;config/config.php&#39;;//包含核心框架類(lèi)require FRAME_PATH . &#39;Core.php&#39;;// 實(shí)例化核心類(lèi)
$fast = new Core;
$fast->run();

以上文件都其實(shí)可以直接在 index.php 文件中包含,常量也可以直接在 index.php 中定義,我們這么做的原因是為了在后期管理和拓展中更加的方便,所以把需要在一開(kāi)始的時(shí)候就加載運(yùn)行的程序統(tǒng)一放到一個(gè)單獨(dú)的文件中引用。

先來(lái)看看config文件下的 config .php 文件,該文件的主要作用是設(shè)置一些程序的配置項(xiàng)及數(shù)據(jù)庫(kù)連接等,主要內(nèi)容為:

<?php 
/** 變量配置 **/
 
define(&#39;DB_NAME&#39;, &#39;todo&#39;);
define(&#39;DB_USER&#39;, &#39;root&#39;);
define(&#39;DB_PASSWORD&#39;, &#39;root&#39;);
define(&#39;DB_HOST&#39;, &#39;localhost&#39;);

應(yīng)該說(shuō) config.php 涉及到的內(nèi)容并不多,不過(guò)是一些基礎(chǔ)數(shù)據(jù)庫(kù)的設(shè)置,再來(lái)看看 fastphp下的共用框架入口文件 Core.php 應(yīng)該怎么寫(xiě)。

<?php/**
 * FastPHP核心框架
 */class Core
{    // 運(yùn)行程序    function run()
    {
        spl_autoload_register(array($this, &#39;loadClass&#39;));
        $this->setReporting();
        $this->removeMagicQuotes();
        $this->unregisterGlobals();
        $this->Route();
    }    // 路由處理    function Route()
    {
        $controllerName = &#39;Index&#39;;
        $action = &#39;index&#39;;        if (!empty($_GET[&#39;url&#39;])) {
            $url = $_GET[&#39;url&#39;];
            $urlArray = explode(&#39;/&#39;, $url);            
            // 獲取控制器名
            $controllerName = ucfirst($urlArray[0]);            
            // 獲取動(dòng)作名
            array_shift($urlArray);
            $action = empty($urlArray[0]) ? &#39;index&#39; : $urlArray[0];            
            //獲取URL參數(shù)
            array_shift($urlArray);
            $queryString = empty($urlArray) ? array() : $urlArray;
        }        // 數(shù)據(jù)為空的處理
        $queryString  = empty($queryString) ? array() : $queryString;        // 實(shí)例化控制器
        $controller = $controllerName . &#39;Controller&#39;;
        $dispatch = new $controller($controllerName, $action);        // 如果控制器存和動(dòng)作存在,這調(diào)用并傳入U(xiǎn)RL參數(shù)        if ((int)method_exists($controller, $action)) {
            call_user_func_array(array($dispatch, $action), $queryString);
        } else {            exit($controller . "控制器不存在");
        }
    }    // 檢測(cè)開(kāi)發(fā)環(huán)境    function setReporting()
    {        if (APP_DEBUG === true) {
            error_reporting(E_ALL);
            ini_set(&#39;display_errors&#39;,&#39;On&#39;);
        } else {
            error_reporting(E_ALL);
            ini_set(&#39;display_errors&#39;,&#39;Off&#39;);
            ini_set(&#39;log_errors&#39;, &#39;On&#39;);
            ini_set(&#39;error_log&#39;, RUNTIME_PATH. &#39;logs/error.log&#39;);
        }
    }    // 刪除敏感字符    function stripSlashesDeep($value)
    {
        $value = is_array($value) ? array_map(&#39;stripSlashesDeep&#39;, $value) : stripslashes($value);        return $value;
    }    // 檢測(cè)敏感字符并刪除    function removeMagicQuotes()
    {        if ( get_magic_quotes_gpc()) {
            $_GET = stripSlashesDeep($_GET );
            $_POST = stripSlashesDeep($_POST );
            $_COOKIE = stripSlashesDeep($_COOKIE);
            $_SESSION = stripSlashesDeep($_SESSION);
        }
    }    // 檢測(cè)自定義全局變量(register globals)并移除    function unregisterGlobals()
    {        if (ini_get(&#39;register_globals&#39;)) {
            $array = array(&#39;_SESSION&#39;, &#39;_POST&#39;, &#39;_GET&#39;, &#39;_COOKIE&#39;, &#39;_REQUEST&#39;, &#39;_SERVER&#39;, &#39;_ENV&#39;, &#39;_FILES&#39;);           foreach ($array as $value) {                foreach ($GLOBALS[$value] as $key => $var) {                    if ($var === $GLOBALS[$key]) {                        unset($GLOBALS[$key]);
                    }
                }
            }
        }
    }    // 自動(dòng)加載控制器和模型類(lèi) 
    static function loadClass($class)
    {
        $frameworks = FRAME_PATH . $class . &#39;.class.php&#39;;
        $controllers = APP_PATH . &#39;application/controllers/&#39; . $class . &#39;.class.php&#39;;
        $models = APP_PATH . &#39;application/models/&#39; . $class . &#39;.class.php&#39;;        if (file_exists($frameworks)) {            // 加載框架核心類(lèi)            include $frameworks;
        } elseif (file_exists($controllers)) {            // 加載應(yīng)用控制器類(lèi)            include $controllers;
        } elseif (file_exists($models)) {            //加載應(yīng)用模型類(lèi)            include $models;
        } else {            /* 錯(cuò)誤代碼 */
        }
    }
}

下面重點(diǎn)講解主請(qǐng)求方法 callHook(),首先我們想看看我們的 URL 會(huì)這樣:

yoursite.com/controllerName/actionName/queryString

callHook()的作用就是,從全局變量 GET[′url′]變量中獲取URL,并將其分割成三部分:GET[′url′]變量中獲取URL,并將其分割成三部分:controller、action和action和queryString。

例如,URL鏈接為:todo.com/item/view/1/first-item,那么

$controller 就是:item

$action 就是:view

查詢(xún)字符串Query String就是:array(1, first-item)

分割完成后,會(huì)實(shí)例化一個(gè)新的控制器:$controller.'Controller'(其中“.”是連字符),并調(diào)用其方法 $action。

3.6 控制器/Controller基類(lèi)

接下來(lái)的操作就是在 fastphp 中建立程序所需的基類(lèi),包括控制器、模型和視圖的基類(lèi)。

新建控制器基類(lèi)為 Controller.class.php,控制器的主要功能就是總調(diào)度,具體具體內(nèi)容如下:

<?php 
/**
 * 控制器基類(lèi)
 */class Controller
{    protected $_controller;    protected $_action;    protected $_view; 
    // 構(gòu)造函數(shù),初始化屬性,并實(shí)例化對(duì)應(yīng)模型    function __construct($controller, $action)
    {
        $this->_controller = $controller;
        $this->_action = $action;
        $this->_view = new View($controller, $action);
    }    // 分配變量    function assign($name, $value)
    {
        $this->_view->assign($name, $value);
    }    // 渲染視圖    function __destruct()
    {
        $this->_view->render();
    }
}

Controller 類(lèi)實(shí)現(xiàn)所有控制器、模型和視圖(View類(lèi))的通信。在執(zhí)行析構(gòu)函數(shù)時(shí),我們可以調(diào)用 render() 來(lái)顯示視圖(view)文件。

3.7 模型Model基類(lèi)

新建模型基類(lèi)為 Model.class.php,模型基類(lèi) Model.class.php 代碼如下:

<?phpclass Model extends Sql
{    protected $_model;    protected $_table; 
    function __construct()
    {        // 連接數(shù)據(jù)庫(kù)
        $this->connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);        
        // 獲取模型名稱(chēng)
        $this->_model = get_class($this);
        $this->_model = rtrim($this->_model, &#39;Model&#39;);        
        // 數(shù)據(jù)庫(kù)表名與類(lèi)名一致
        $this->_table = strtolower($this->_model);
    } 
    function __destruct()
    {
    }
}

考慮到模型需要對(duì)數(shù)據(jù)庫(kù)進(jìn)行處理,所以單獨(dú)建立一個(gè)數(shù)據(jù)庫(kù)基類(lèi) Sql.class.php,模型基類(lèi)繼承 Sql.class.php,代碼如下:

<?php 

class Sql
{    protected $_dbHandle;    protected $_result;    // 連接數(shù)據(jù)庫(kù)    public function connect($host, $user, $pass, $dbname)
    {        try {
            $dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname);
            $this->_dbHandle = new PDO($dsn, $user, $pass, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
        } catch (PDOException $e) {            exit(&#39;錯(cuò)誤: &#39; . $e->getMessage());
        }
    }    // 查詢(xún)所有    public function selectAll()
    {
        $sql = sprintf("select * from `%s`", $this->_table);
        $sth = $this->_dbHandle->prepare($sql);
        $sth->execute();        return $sth->fetchAll();
    }    // 根據(jù)條件 (id) 查詢(xún)    public function select($id)
    {
        $sql = sprintf("select * from `%s` where `id` = &#39;%s&#39;", $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` = &#39;%s&#39;", $this->_table, $id);
        $sth = $this->_dbHandle->prepare($sql);
        $sth->execute();        return $sth->rowCount();
    }    // 自定義SQL查詢(xún),返回影響的行數(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` = &#39;%s&#39;", $this->_table, $this->formatUpdate($data), $id);        return $this->query($sql);
    }    // 將數(shù)組轉(zhuǎn)換成插入格式的sql語(yǔ)句    private function formatInsert($data)
    {
        $fields = array();
        $values = array();        foreach ($data as $key => $value) {
            $fields[] = sprintf("`%s`", $key);
            $values[] = sprintf("&#39;%s&#39;", $value);
        }

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

應(yīng)該說(shuō),Sql.class.php 是框架的核心部分。為什么?因?yàn)橥ㄟ^(guò)它,我們創(chuàng)建了一個(gè) SQL 抽象層,可以大大減少了數(shù)據(jù)庫(kù)的編程工作。雖然 PDO 接口本來(lái)已經(jīng)很簡(jiǎn)潔,但是抽象之后框架的可靈活性更高。

3.8 視圖View類(lèi)

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

<?php/**
 * 視圖基類(lèi)
 */class View
{    protected $variables = array();    protected $_controller;    protected $_action;    function __construct($controller, $action)
    {
        $this->_controller = $controller;
        $this->_action = $action;
    } 
    /** 分配變量 **/    function assign($name, $value)
    {
        $this->variables[$name] = $value;
    } 
    /** 渲染顯示 **/    function render()
    {
        extract($this->variables);
        $defaultHeader = APP_PATH . &#39;application/views/header.php&#39;;
        $defaultFooter = APP_PATH . &#39;application/views/footer.php&#39;;
        $controllerHeader = APP_PATH . &#39;application/views/&#39; . $this->_controller . &#39;/header.php&#39;;
        $controllerFooter = APP_PATH . &#39;application/views/&#39; . $this->_controller . &#39;/footer.php&#39;;        
        // 頁(yè)頭文件        if (file_exists($controllerHeader)) {            include ($controllerHeader);
        } else {            include ($defaultHeader);
        }        // 頁(yè)內(nèi)容文件        include (APP_PATH . &#39;application/views/&#39; . $this->_controller . &#39;/&#39; . $this->_action . &#39;.php&#39;);        
        // 頁(yè)腳文件        if (file_exists($controllerFooter)) {            include ($controllerFooter);
        } else {            include ($defaultFooter);
        }
    }
}

這樣我們的核心的PHP MVC框架就編寫(xiě)完成了,下面我們開(kāi)始編寫(xiě)應(yīng)用來(lái)測(cè)試框架功能。

4 應(yīng)用

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

在 SQL 中新建一個(gè) todo 數(shù)據(jù)庫(kù),使用下面的語(yǔ)句增加 item 數(shù)據(jù)表并插入2條記錄:

CREATE DATABASE `todo` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;USE `todo`;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, &#39;Hello World.&#39;);INSERT INTO `item` VALUES(2, &#39;Lets go!&#39;);

4.2 部署模型

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

<?phpclass ItemModel extends Model
{    /* 業(yè)務(wù)邏輯層實(shí)現(xiàn) */
}

模型內(nèi)容為空。因?yàn)?Item 模型繼承了 Model,所以它擁有 Model 的所有功能。

4.3 部署控制器

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

<?php 
class ItemController extends Controller
{    // 首頁(yè)方法,測(cè)試框架自定義DB查詢(xún)    public function index()
    {
        $items = (new ItemModel)->selectAll();

        $this->assign(&#39;title&#39;, &#39;全部條目&#39;);
        $this->assign(&#39;items&#39;, $items);
    }    
    // 添加記錄,測(cè)試框架DB記錄創(chuàng)建(Create)    public function add()
    {
        $data[&#39;item_name&#39;] = $_POST[&#39;value&#39;];
        $count = (new ItemModel)->add($data);

        $this->assign(&#39;title&#39;, &#39;添加成功&#39;);
        $this->assign(&#39;count&#39;, $count);
    }    
    // 查看記錄,測(cè)試框架DB記錄讀取(Read)    public function view($id = null)
    {
        $item = (new ItemModel)->select($id);

        $this->assign(&#39;title&#39;, &#39;正在查看&#39; . $item[&#39;item_name&#39;]);
        $this->assign(&#39;item&#39;, $item);
    }    
    // 更新記錄,測(cè)試框架DB記錄更新(Update)    public function update()
    {
        $data = array(&#39;id&#39; => $_POST[&#39;id&#39;], &#39;item_name&#39; => $_POST[&#39;value&#39;]);
        $count = (new ItemModel)->update($data[&#39;id&#39;], $data);

        $this->assign(&#39;title&#39;, &#39;修改成功&#39;);
        $this->assign(&#39;count&#39;, $count);
    }    
    // 刪除記錄,測(cè)試框架DB記錄刪除(Delete)    public function delete($id = null)
    {
        $count = (new ItemModel)->delete($id);

        $this->assign(&#39;title&#39;, &#39;刪除成功&#39;);
        $this->assign(&#39;count&#39;, $count);
    }
}

4.4 部署視圖

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

header.php,內(nèi)容:

<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:blue;            font-family:georgia,times;            font-size:20px;            font-weight:normal;            line-height:1.2em;            text-decoration:none;
         } 
        a:hover {            text-decoration:underline;
        }        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,內(nèi)容:
</body></html>

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

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

<form action="<?php echo APP_URL ?>/item/add" method="post">    <input type="text" value="點(diǎn)擊添加" onclick="this.value=&#39;&#39;" name="value">    <input type="submit" value="添加"></form><br/><br/><?php $number = 0?> 
<?php foreach ($items as $item): ?>    <a class="big" href="<?php echo APP_URL ?>/item/view/<?php echo $item[&#39;id&#39;] ?>" title="點(diǎn)擊修改">        <span class="item">            <?php echo ++$number ?>            <?php echo $item[&#39;item_name&#39;] ?>        </span>    </a>
    ----    <a class="big" href="<?php echo APP_URL ?>/item/delete/<?php echo $item[&#39;id&#39;]?>">刪除</a><br/><?php endforeach ?>
add.php,添加記錄,內(nèi)容:
<a class="big" href="<?php echo APP_URL ?>/item/index">成功添加<?php echo $count ?>條記錄,點(diǎn)擊返回</a>
view.php,查看單條記錄,內(nèi)容:
<form action="<?php echo APP_URL ?>/item/update" method="post">    <input type="text" name="value" value="<?php echo $item[&#39;item_name&#39;] ?>">    <input type="hidden" name="id" value="<?php echo $item[&#39;id&#39;] ?>">    <input type="submit" value="修改"></form><a class="big" href="<?php echo APP_URL ?>/item/index">返回</a>
update.php,更改記錄,內(nèi)容:
<a class="big" href="<?php echo APP_URL ?>/item/index">成功修改<?php echo $count ?>項(xiàng),點(diǎn)擊返回</a>
delete.php,刪除記錄,內(nèi)容:
<a href="<?php echo APP_URL ?>/item/index">成功刪除<?php echo $count ?>項(xiàng),點(diǎn)擊返回</a>

4.5 應(yīng)用測(cè)試

這樣,在瀏覽器中訪(fǎng)問(wèn) todo 程序:http://localhost/todo/item/index/,就可以看到效果了。

Write the PHP framework step by step and gain an in-depth understanding of the MVC operation process

以上代碼已經(jīng)全部發(fā)布到 github 上,關(guān)鍵部分加航了注釋?zhuān)瑐}(cāng)庫(kù)地址:https://github.com/yeszao/fastphp,歡迎克隆、提交。

要設(shè)計(jì)更好的MVC,或使用得更加規(guī)范,請(qǐng)看《MVC架構(gòu)的職責(zé)劃分原則》。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Jun 04, 2024 pm 03:36 PM

The choice of PHP framework depends on project needs and developer skills: Laravel: rich in features and active community, but has a steep learning curve and high performance overhead. CodeIgniter: lightweight and easy to extend, but has limited functionality and less documentation. Symfony: Modular, strong community, but complex, performance issues. ZendFramework: enterprise-grade, stable and reliable, but bulky and expensive to license. Slim: micro-framework, fast, but with limited functionality and a steep learning curve.

Performance differences of PHP frameworks in different development environments Performance differences of PHP frameworks in different development environments Jun 05, 2024 pm 08:57 PM

There are differences in the performance of PHP frameworks in different development environments. Development environments (such as local Apache servers) suffer from lower framework performance due to factors such as lower local server performance and debugging tools. In contrast, a production environment (such as a fully functional production server) with more powerful servers and optimized configurations allows the framework to perform significantly better.

PHP Frameworks and Microservices: Cloud Native Deployment and Containerization PHP Frameworks and Microservices: Cloud Native Deployment and Containerization Jun 04, 2024 pm 12:48 PM

Benefits of combining PHP framework with microservices: Scalability: Easily extend the application, add new features or handle more load. Flexibility: Microservices are deployed and maintained independently, making it easier to make changes and updates. High availability: The failure of one microservice does not affect other parts, ensuring higher availability. Practical case: Deploying microservices using Laravel and Kubernetes Steps: Create a Laravel project. Define microservice controllers. Create Dockerfile. Create a Kubernetes manifest. Deploy microservices. Test microservices.

Integration of PHP frameworks with DevOps: the future of automation and agility Integration of PHP frameworks with DevOps: the future of automation and agility Jun 05, 2024 pm 09:18 PM

Integrating PHP frameworks with DevOps can improve efficiency and agility: automate tedious tasks, free up personnel to focus on strategic tasks, shorten release cycles, accelerate time to market, improve code quality, reduce errors, enhance cross-functional team collaboration, and break down development and operations silos

PHP Frameworks and Artificial Intelligence: A Developer's Guide PHP Frameworks and Artificial Intelligence: A Developer's Guide Jun 04, 2024 pm 12:47 PM

Use a PHP framework to integrate artificial intelligence (AI) to simplify the integration of AI in web applications. Recommended framework: Laravel: lightweight, efficient, and powerful. CodeIgniter: Simple and easy to use, suitable for small applications. ZendFramework: Enterprise-level framework with complete functions. AI integration method: Machine learning model: perform specific tasks. AIAPI: Provides pre-built functionality. AI library: handles AI tasks.

Which PHP framework offers the most comprehensive extension library for rapid development? Which PHP framework offers the most comprehensive extension library for rapid development? Jun 04, 2024 am 10:45 AM

The PHP framework extension library provides four frameworks for selection: Laravel: Known for its vast ecosystem and third-party packages, it provides authentication, routing, validation and other extensions. Symfony: Highly modular, extending functionality through reusable "Bundles", covering areas such as authentication and forms. CodeIgniter: lightweight and high-performance, providing practical extensions such as database connection and form validation. ZendFramework: Powerful enterprise-level features, with extensions such as authentication, database connection, RESTfulAPI support, etc.

Application of PHP framework in agile development and large-scale projects Application of PHP framework in agile development and large-scale projects Jun 04, 2024 pm 01:42 PM

The PHP framework is widely used in agile development and large-scale projects, providing advantages such as agility, scalability, and security. For example, in e-commerce websites, the Laravel framework can quickly create prototypes, handle complex business logic, ensure security, and extend functionality. By leveraging predefined components and design patterns, PHP frameworks facilitate developers to build scalable and well-maintained applications.

Comparison of PHP framework and Python framework Comparison of PHP framework and Python framework Jun 05, 2024 pm 09:09 PM

PHP and Python frameworks differ in language features, framework ecology, and features. PHP is primarily used for web development and is easy to learn; Python has an extensive library ecosystem. Popular PHP frameworks include Laravel, CodeIgniter, and Symfony; Python frameworks include Django, Flask, and Web2py. In practical cases, Laravel uses the command line to generate blog models and views, while Django uses DjangoAdmin and Python scripts to create blogs.

See all articles