首页 技术 正文
技术 2022年11月16日
0 收藏 975 点赞 2,810 浏览 13213 个字
1 什么是MVCMVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller)。PHP中MVC模式也称Web MVC,从上世纪70年代进化而来。MVC的目的是实现一种动态的程序设计,便于后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能。除此之外,此模式通过对复杂度的简化,使程序结构更加直观。MVC各部分的职能:模型Model – 管理大部分的业务逻辑和所有的数据库逻辑。模型提供了连接和操作数据库的抽象层。
控制器Controller - 负责响应用户请求、准备数据,以及决定如何展示数据。
视图View – 负责渲染数据,通过HTML方式呈现给用户。
MVC流程图一个典型的Web MVC流程:Controller截获用户发出的请求;
Controller调用Model完成状态的读写操作;
Controller把数据传递给View;
View渲染最终结果并呈献给用户。
2 为什么要自己开发MVC框架网络上有大量优秀的MVC框架可供使用,本教程并不是为了开发一个全面的、终极的MVC框架解决方案,而是将它看作是一个很好的从内部学习PHP的机会,在此过程中,你将学习面向对象编程和MVC设计模式,并学习到开发中的一些注意事项。更重要的是,通过自制MVC框架,你可以完全控制你的框架,并将你的想法融入到你开发的框架中。虽然不一定是最好的,但是你可以按照自己的方式开发各种功能。3 开始开发自己的MVC框架3.1 目录准备在开始开发前,让我们先来把项目建立好,假设我们建立的项目为 project,MVC的框架命名为 fastphp,那么接下来,第一步要把目录结构设置好。project WEB部署目录
├─application 应用目录
│ ├─controllers 控制器目录
│ ├─models 模块目录
│ ├─views 视图目录
├─config 配置文件目录
├─fastphp 核心框架目录
├─runtime 运行目录
│ ├─caches 缓存文目录
│ ├─logs 日志目录
│ ├─sessions 缓存目录
├─index.php 入口文件
教程中不会用runtime目录,不过为了让程序更具可拓展性,一开始把目录设置好非常有必要。3.2 代码规范在目录设置好以后,我们接下来规定一下代码的规范:MySQL的表名需小写或小写加下划线,如:item,car_orders。
模块名(Models)需用大驼峰命名法,即首字母大写,并在名称后添加Model,如:ItemModel,CarModel。
控制器(Controllers)需用大驼峰命名法,即首字母大写,并在名称后添加Controller,如:ItemController,CarController。
方法名(Action)需用小驼峰命名法,即首字母小写,如:index,indexPost。
视图(Views)部署结构为控制器名/行为名,如:item/view.php,car/buy.php。
上述规则是为了程序能更好地相互调用。接下来就开始真正的PHP MVC编程了。3.3 重定向重定向的目的是,将所有的数据请求都发送给 index.php 文件,在 project 目录下新建一个 .htaccess 文件,文件内容为:<IfModule mod_rewrite.c>
RewriteEngine On # 如果访问的文件存在,则直接访问,不重定向
RewriteCond %{REQUEST_FILENAME} !-f
# 如果访问的目录存在,则直接访问,不重定向
RewriteCond %{REQUEST_FILENAME} !-d # 如果访问的文件或目录不存在,则重定向所有请求
# 到:index.php?url=<PARAMS>。
# 例如:当我们请求<域名>item/index时,实际上是
# 请求<域名>index.php?url=item/index,在PHP中
# 用 GET['url'] 就能拿到字符串item/index
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>
这样做的主要原因有:
程序有单一的入口;
除静态程序,其他所有程序都重定向到 index.php?url=<参数> 上;
可以用来生成利于SEO的URL。
3.4 入口文件接下来,创建一个入口文件。在 public 目录下新建 index.php 文件,文件内容为:<?php // 应用目录为当前目录
define('APP_PATH', __DIR__.'/');// 开启调试模式
define('APP_DEBUG', true);// 网站根URL
define('APP_URL', 'http://localhost/project');// 加载框架
require './fastphp/Fastphp.php';
注意,上面的PHP代码中,并没有添加PHP结束符号?>,这么做的主要原因是:对于只有 PHP 代码的文件,最好没有结束标志?>,PHP自身并不需要结束符号,不加结束符让程序更加安全,很大程度防止了末尾被注入额外的内容。
3.5 配置文件和主请求在 index.php 中,我们对 fastphp 文件夹下的 Fastphp.php 发起了请求,那么 fastphp.php 文件包含了哪些内容呢?如下:<?php// 初始化常量
defined('FRAME_PATH') or define('FRAME_PATH', __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/');// 包含配置文件
require APP_PATH . 'config/config.php';//包含核心框架类
require FRAME_PATH . 'Core.php';// 实例化核心类
$fast = new Core;
$fast->run();
fastphp.php 的作用就是,预定义一些系统常量、包含配置文件、包含核心框架类文件并实例化。
config 目录下的 config .php 文件就是配置文件,用以设置程序的一些配置项、和数据库连接,主要内容为:<?php// 数据库配置
define('DB_NAME', 'todo');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
再来看看 fastphp下的框架入口文件 Core.php 。
<?php
/**
* fastphp框架核心
*/
class Core
{
// 运行程序
public function run()
{
spl_autoload_register(array($this, 'loadClass'));
$this->setReporting();
$this->removeMagicQuotes();
$this->unregisterGlobals();
$this->route();
} // 路由处理
public function route()
{
$controllerName = 'Index';
$action = 'index';
$param = array(); $url = isset($_GET['url']) ? $_GET['url'] : false;
if ($url) {
// 使用“/”分割字符串,并保存在数组中
$urlArray = explode('/', $url);
// 删除空的数组元素
$urlArray = array_filter($urlArray); // 获取控制器名
$controllerName = ucfirst($urlArray[0]); // 获取动作名
array_shift($urlArray);
$action = $urlArray ? $urlArray[0] : 'index'; // 获取URL参数
array_shift($urlArray);
$param = $urlArray ? $urlArray : array();
} // 实例化控制器
$controller = $controllerName . 'Controller';
$dispatch = new $controller($controllerName, $action); // 如果控制器存和动作存在,这调用并传入URL参数
if ((int)method_exists($controller, $action)) {
call_user_func_array(array($dispatch, $action), $param);
} else {
exit($controller . "控制器不存在");
}
} // 检测开发环境
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');
ini_set('error_log', RUNTIME_PATH. 'logs/error.log');
}
} // 删除敏感字符
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)并移除
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]);
}
}
}
}
} // 自动加载控制器和模型类
public static function loadClass($class)
{
$frameworks = FRAME_PATH . $class . '.class.php';
$controllers = APP_PATH . 'application/controllers/' . $class . '.class.php';
$models = APP_PATH . 'application/models/' . $class . '.class.php'; if (file_exists($frameworks)) {
// 加载框架核心类
include $frameworks;
} elseif (file_exists($controllers)) {
// 加载应用控制器类
include $controllers;
} elseif (file_exists($models)) {
//加载应用模型类
include $models;
} else {
// 错误代码
}
}
}
下面重点讲解主请求方法 route(),它也称路由方法,作用是:截取URL,并解析出控制器名、方法名和URL参数。假设我们的 URL 是这样:yoursite.com/controllerName/actionName/queryString
当浏览器访问上面的URL,route()从全局变量 $_GET['url']中获取到字符串controllerName/actionName/queryString,并将其分割成三部分:controller、action 和 queryString。例如,URL链接为:yoursite.com/item/view/1/hello,那么route()分割之后,控制器名就是:item
方法名就是:view
URL参数就是:array(1, hello)
分割完成后,再实例化控制器:itemController,并调用方法 view。3.6 Controller基类接下来,就是在 fastphp 中创建MVC基类,包括控制器、模型和视图三个基类。新建控制器基类,文件名 Controller.class.php,主要功能就是总调度,内容如下:<?php
/**
* 控制器基类
*/
class Controller
{
protected $_controller;
protected $_action;
protected $_view; // 构造函数,初始化属性,并实例化对应模型
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 类实现所有控制器、模型和视图的通信。这样,在控制器子类中,我们就可以调用$this-> render() 来显示视图(view)文件。3.7 Model基类新建模型基类,继承自数据库操作类Sql类。模型基类文件名为 Model.class.php,代码如下:<?phpclass Model extends Sql
{
protected $_model;
protected $_table; public function __construct()
{
// 连接数据库
$this->connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // 获取模型类名
$this->_model = get_class($this);
// 删除类名最后的 Model 字符
$this->_model = substr($this->_model, 0, -5); // 数据库表名与类名一致
$this->_table = strtolower($this->_model);
}
}
考虑到模型需要对数据库进行处理,所以单独建立一个数据库基类 Sql.class.php,模型基类继承 Sql.class.php,代码如下:<?php class Sql
{
protected $_dbHandle;
protected $_result;
private $filter = ''; // 连接数据库
public function connect($host, $user, $pass, $dbname)
{
try {
$dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname);
$option = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$this->_dbHandle = new PDO($dsn, $user, $pass, $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();
} // 根据条件 (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 内容如下:<?php
/**
* 视图基类
*/
class View
{
protected $variables = array();
protected $_controller;
protected $_action; function __construct($controller, $action)
{
$this->_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';
$defaultLayout = APP_PATH . 'application/views/layout.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);
} // 页内容文件
if (file_exists($controllerLayout)) {
include ($controllerLayout);
} else {
include ($defaultLayout);
} // 页脚文件
if (file_exists($controllerFooter)) {
include ($controllerFooter);
} else {
include ($defaultFooter);
}
}
}
这样,核心的PHP MVC框架核心就完成了。下面我们编写应用来测试框架功能。4 应用4.1 数据库部署在 SQL 中新建一个 project 数据库,增加一个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 目录中创建一个 ItemModel.php 模型,内容如下:<?phpclass ItemModel extends Model
{
/* 业务逻辑层实现 */
}
模型内容为空。因为 Item 模型继承了 Model基类,所以它拥有 Model 类的所有功能。4.3 部署控制器在 controllers 目录下创建一个 ItemController.php 控制器,内容如下:<?phpclass ItemController extends Controller
{
// 首页方法,测试框架自定义DB查询
public function index()
{
$items = (new ItemModel)->selectAll(); $this->assign('title', '全部条目');
$this->assign('items', $items);
$this->render();
} // 添加记录,测试框架DB记录创建(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 内容:<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 内容:</body>
</html>
然后,在 views/item 创建以下几个视图文件。index.php,浏览数据库内 item 表的所有记录,内容:<form action="<?php echo APP_URL ?>/item/add" method="post">
<input type="text" value="点击添加" onclick="this.value=''" 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['id'] ?>" rel="external nofollow" title="点击修改">
<span class="item">
<?php echo ++$number ?>
<?php echo $item['item_name'] ?>
</span>
</a>
----
<a class="big" href="<?php echo APP_URL ?>/item/delete/<?php echo $item['id']?>" rel="external nofollow" >删除</a>
<br/>
<?php endforeach ?>
add.php,添加记录,内容:<a class="big" href="<?php echo APP_URL ?>/item/index" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >成功添加<?php echo $count ?>条记录,点击返回</a>
view.php,查看单条记录,内容:<form action="<?php echo APP_URL ?>/item/update" method="post">
<input type="text" name="value" value="<?php echo $item['item_name'] ?>">
<input type="hidden" name="id" value="<?php echo $item['id'] ?>">
<input type="submit" value="修改">
</form><a class="big" href="<?php echo APP_URL ?>/item/index" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >返回</a>
update.php,更改记录,内容:<a class="big" href="<?php echo APP_URL ?>/item/index" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >成功修改<?php echo $count ?>项,点击返回</a>
delete.php,删除记录,内容:<a href="<?php echo APP_URL ?>/item/index" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >成功删除<?php echo $count ?>项,点击返回</a>

网址:http://www.awaimai.com/128.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289