手把手编写PHP框架 深入了解MVC运行流程
1 什么是MVC
MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller)。
PHP中MVC模式也称Web MVC,从上世纪70年代进化而来。MVC的目的是实现一种动态的程序设计,便于后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能。除 此之外,此模式通过对复杂度的简化,使程序结构更加直观。软件系统通过对自身基本部份分离的同时,也赋予了各个基本部分应有的功能。
MVC各部分的职能:
"text-align: center">
一个典型的Web MVC流程:
1.Controller截获用户发出的请求;
2.Controller调用Model完成状态的读写操作;
3.Controller把数据传递给View;
4.View渲染最终结果并呈献给用户。
2 为什么要自己开发MVC框架
网络上有大量优秀的MVC框架可供使用,本教程并不是为了开发一个全面的、终极的MVC框架解决方案,而是将它看作是一个很好的从内部学习PHP的机会,在此过程中,你将学习面向对象编程和MVC设计模式,并学习到开发中的一些注意事项。
更重要的是,你可以完全控制你的框架,并将你的想法融入到你开发的框架中。虽然不一定是做好的,但是你可以按照你的方式去开发功能和模块。
3 开始开发自己的MVC框架
3.1 目录准备
在开始开发前,让我们先来把项目建立好,假设我们建立的项目为 todo,MVC的框架可以命名为 FastPHP,那么接下来的第一步就是把目录结构先设置好。
虽然在这个教程中不会使用到上面的所有的目录,但是为了以后程序的可拓展性,在一开始就把程序目录设置好使非常必要的。下面就具体说说每个目录的作用:
"htmlcode">
<IfModule mod_rewrite.c>
RewriteEngine On
# 确保请求路径不是一个文件名或目录
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 重定向所有请求到 index.php"htmlcode">
<"htmlcode">
<"htmlcode">
<"htmlcode">
<"控制器不存在");
}
}
// 检测开发环境
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) "htmlcode">
<"htmlcode">
<"htmlcode">
<"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('错误: ' . $e->getMessage());
}
}
// 查询所有
public function selectAll()
{
$sql = sprintf("select * from `%s`", $this->_table);
$sth = $this->_dbHandle->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
// 根据条件 (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();
}
// 根据条件 (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查询,返回影响的行数
public function query($sql)
{
$sth = $this->_dbHandle->prepare($sql);
$sth->execute();
return $sth->rowCount();
}
// 新增数据
public function add($data)
{
$sql = sprintf("insert into `%s` %s", $this->_table, $this->formatInsert($data));
return $this->query($sql);
}
// 修改数据
public function update($id, $data)
{
$sql = sprintf("update `%s` set %s where `id` = '%s'", $this->_table, $this->formatUpdate($data), $id);
return $this->query($sql);
}
// 将数组转换成插入格式的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);
}
// 将数组转换成更新格式的sql语句
private function formatUpdate($data)
{
$fields = array();
foreach ($data as $key => $value) {
$fields[] = sprintf("`%s` = '%s'", $key, $value);
}
return implode(',', $fields);
}
}
应该说,Sql.class.php 是框架的核心部分。为什么?因为通过它,我们创建了一个 SQL 抽象层,可以大大减少了数据库的编程工作。虽然 PDO 接口本来已经很简洁,但是抽象之后框架的可灵活性更高。
3.8 视图View类
视图类 View.class.php 内容如下:
<"htmlcode">
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, 'Hello World.');
INSERT INTO `item` VALUES(2, 'Lets go!');
4.2 部署模型
然后,我们还需要在 models 目录中创建一个 ItemModel.php 模型,内容如下:
<"htmlcode">
<"htmlcode">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><"htmlcode">
<form action="<" method="post">
<input type="text" value="点击添加" onclick="this.value=''" name="value">
<input type="submit" value="添加">
</form>
<br/><br/>
<"big" href="<" title="点击修改">
<span class="item">
<"big" href="<">删除</a>
<br/>
<"color: #800000"><a class="big" href="<">成功添加<"htmlcode">
<form action="<" method="post">
<input type="text" name="value" value="<">
<input type="hidden" name="id" value="<">
<input type="submit" value="修改">
</form>
<a class="big" href="<">返回</a>
update.php,更改记录,内容:
<a class="big" href="<">成功修改<"color: #800000"><a href="<">成功删除<"nofollow" target="_blank" href="https://github.com/yeszao/fastphp">https://github.com/yeszao/fastphp,欢迎克隆、提交。
要设计更好的MVC,或使用得更加规范,请看《MVC架构的职责划分原则》 。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇:PHP 中 DOMDocument保存xml时中文出现乱码问题的解决方案
下一篇:PHP 接入支付宝即时到账功能
