博客列表 >12月06日_简单MVC框架实现

12月06日_简单MVC框架实现

fkkf467
fkkf467原创
2019年12月12日 12:55:16636浏览

1. 目录结构

2. 代码文件

Db.php

  1. <?php
  2. // 定义命名空间
  3. namespace goods\model;
  4. // 引入外部类的别名
  5. use PDO;
  6. use PDOException;
  7. // 数据库连接类
  8. // 用单例模式实现
  9. class Db
  10. {
  11. // 连接属性
  12. public static $pdo = null;
  13. // 连接方法
  14. private function connect()
  15. {
  16. try {
  17. self::$pdo = new PDO('mysql:host=localhost;dbname=test','root','root');
  18. }catch (PDOException $e){
  19. die('数据库连接失败,错误信息为:' . $e->getMessage());
  20. }
  21. }
  22. // 构造方法私有化
  23. private function __construct()
  24. {
  25. $this->connect();
  26. }
  27. public static function getInstance()
  28. {
  29. if (is_null(self::$pdo)){
  30. new self();
  31. }
  32. return self::$pdo;
  33. }
  34. // 禁用克隆魔术方法
  35. private function __clone()
  36. {
  37. }
  38. }

Model.php

  1. <?php
  2. namespace goods\model;
  3. require 'Db.php';
  4. use PDO;
  5. // 公共模型类
  6. class Model
  7. {
  8. public $pdo = null;
  9. // 该属性用于获取本类的类名
  10. public $className = self::class;
  11. // 构造方法实现数据库连接
  12. public function __construct()
  13. {
  14. $this->pdo = Db::getInstance();
  15. }
  16. // 查询多条记录
  17. public function select($table, $where = '', $order = '', $limit = '')
  18. {
  19. // 创建SQL语句
  20. $sql = 'SELECT * FROM ' . $table;
  21. // 查询条件
  22. if (!empty($where)) {
  23. $sql .= ' WHERE ' . $where;
  24. }
  25. // 排序方式
  26. if (!empty($order)) {
  27. $sql .= ' ORDER BY ' . $order;
  28. }
  29. // 分页
  30. if (!empty($limit)) {
  31. $sql .= ' LIMIT ' . $limit;
  32. }
  33. $sql .= ';';
  34. // 创建PDO预处理对象
  35. $stmt = $this->pdo->prepare($sql);
  36. // 执行查询操作
  37. if ($stmt->execute()) {
  38. if ($stmt->rowCount() > 0) {
  39. $stmt->setFetchMode(PDO::FETCH_CLASS, $this->className);
  40. return $stmt->fetchAll();
  41. }
  42. }
  43. return '查询失败';
  44. }
  45. // 查询单条
  46. public function find($table, $where = '')
  47. {
  48. $sql = 'SELECT * FROM ' . $table;
  49. if (!empty($where)) {
  50. $sql .= ' WHERE ' . $where;
  51. }
  52. $sql .= ' LIMIT 1;';
  53. $stmt = $this->pdo->prepare($sql);
  54. if ($stmt->execute()) {
  55. if ($stmt->rowCount() > 0) {
  56. $stmt->setFetchMode(PDO::FETCH_CLASS, $this->className);
  57. return $stmt->fetch();
  58. }
  59. }
  60. return '查询失败';
  61. }
  62. // 新增记录
  63. public function insert($table, $data = [])
  64. {
  65. $sql = 'INSERT INTO ' . $table . ' SET ';
  66. if (is_array($data)) {
  67. foreach ($data as $k => $v) {
  68. $sql .= "{$k}='{$v}', ";
  69. }
  70. } else {
  71. return '要以关联数组形式传入数据';
  72. }
  73. $sql = rtrim(trim($sql), ',') . ';';
  74. $stmt = $this->pdo->prepare($sql);
  75. if ($stmt->execute()) {
  76. if ($stmt->rowCount() > 0) {
  77. return '添加成功了' . $stmt->rowCount() . '条数据';
  78. }
  79. }
  80. return '添加失败';
  81. }
  82. // 更新数据
  83. public function update($table, $data = [], $where = '')
  84. {
  85. $sql = "UPDATE {$table} SET ";
  86. if (is_array($data)) {
  87. foreach ($data as $k => $v) {
  88. $sql .= "{$k}='{$v}', ";
  89. }
  90. }
  91. $sql = rtrim(trim($sql), ',');
  92. if (!empty($where)) {
  93. $sql .= ' WHERE ' . $where;
  94. }
  95. $stmt = $this->pdo->prepare($sql);
  96. if ($stmt->execute()) {
  97. if ($stmt->rowCount() > 0) {
  98. return '成功修改了' . $stmt->rowCount() . '条数据';
  99. }
  100. }
  101. return '修改失败';
  102. }
  103. // 删除数据
  104. public function delete($table, $where = '')
  105. {
  106. $sql = 'DELETE FROM ' . $table;
  107. if (!empty($where)) {
  108. $sql .= ' WHERE ' . $where;
  109. }
  110. $stmt = $this->pdo->prepare($sql);
  111. if ($stmt->execute()) {
  112. if ($stmt->rowCount() > 0) {
  113. return '删除成功了' . $stmt->rowCount() . '条数据';
  114. }
  115. }
  116. return '删除失败';
  117. }
  118. public function __destruct()
  119. {
  120. $this->pdo = null;
  121. }
  122. }

Goods.php

  1. <?php
  2. namespace goods\model;
  3. require 'Model.php';
  4. // 商品类
  5. class Goods extends Model
  6. {
  7. public $className = self::class;
  8. private $id;
  9. private $name;
  10. private $price;
  11. private $color;
  12. private $content;
  13. private $addtime;
  14. private $status;
  15. public function __construct()
  16. {
  17. parent::__construct();
  18. $this->addtime = date('Y/m/d',$this->addtime);
  19. }
  20. public function __get($name)
  21. {
  22. return $this->$name;
  23. }
  24. public function __set($name, $value)
  25. {
  26. $this->$name = $value;
  27. }
  28. }

View.php

  1. <?php
  2. namespace goods\view;
  3. // 视图类
  4. class View
  5. {
  6. public function showData($data)
  7. {
  8. return $data;
  9. }
  10. public function showTable($data)
  11. {
  12. $table = '<table>';
  13. $table .= '<caption>商品信息表</caption>';
  14. $table .= '<tr><th>商品ID</th><th>商品名称</th><th>商品价格</th><th>商品颜色</th><th>商品描述</th><th>添加时间</th><th>操作</th></tr>';
  15. if (is_array($data)) {
  16. foreach ($data as $value){
  17. $table .= '<tr>';
  18. $table .= '<td>' . $value->id . '</td>';
  19. $table .= '<td>' . $value->name . '</td>';
  20. $table .= '<td>' . $value->price . '</td>';
  21. $table .= '<td>' . $value->color . '</td>';
  22. $table .= '<td>' . $value->content . '</td>';
  23. $table .= '<td>' . $value->addtime . '</td>';
  24. $table .= '<td><a href="./update.php?id=' . $value->id . '" style="margin-right: 20px">修改</a><a href="?id= '. $value->id . '&&func=delete">删除</a></td>';
  25. $table .= '</tr>';
  26. }
  27. } else {
  28. $table .= '<tr>';
  29. $table .= '<td>' . $data->id . '</td>';
  30. $table .= '<td>' . $data->name . '</td>';
  31. $table .= '<td>' . $data->price . '</td>';
  32. $table .= '<td>' . $data->color . '</td>';
  33. $table .= '<td>' . $data->content . '</td>';
  34. $table .= '<td>' . $data->addtime . '</td>';
  35. $table .= '<td><a href="./update.php?id=' . $data->id . '" style="margin-right: 20px">修改</a><a href="?id= '. $data->id . '&&func=delete">删除</a></td>';
  36. $table .= '</tr>';
  37. }
  38. $table .= '</table>';
  39. return $table;
  40. }
  41. public function showResult($result)
  42. {
  43. return '<h4>' . $result . '</h4>';
  44. }
  45. }
  46. echo '<style>
  47. table {
  48. border-collapse: collapse;
  49. border: 1px solid;
  50. margin: 0 auto;
  51. }
  52. caption {
  53. font-size: 1.4rem;
  54. margin-bottom: 10px;
  55. }
  56. tr:first-of-type {
  57. background-color: lightseagreen;
  58. }
  59. th {
  60. height: 40px;
  61. }
  62. td, th {
  63. border: 1px solid;
  64. min-width: 100px;
  65. }
  66. img {
  67. width: 100px;
  68. height: 100px;
  69. }
  70. </style>';

Container.php

  1. <?php
  2. namespace goods\controller;
  3. use Closure;
  4. // 服务容器类
  5. class Container
  6. {
  7. // 容器属性:用来保存创建对象的方法
  8. protected $instance = [];
  9. // 将类的实例化过程绑定到容器中
  10. public function bind($alias, Closure $process)
  11. {
  12. $this->instance[$alias] = $process;
  13. }
  14. // 执行容器中的实例化方法
  15. public function make($alias,$params = [])
  16. {
  17. return call_user_func_array($this->instance[$alias],$params);
  18. }
  19. }

Facade.php

  1. <?php
  2. namespace goods\controller;
  3. //Facade门面类
  4. class Facade
  5. {
  6. protected static $container = null;
  7. protected static $data = [];
  8. protected static $result = null;
  9. // 用服务容器将静态属性初始化
  10. public static function initialize(Container $container)
  11. {
  12. static::$container = $container;
  13. }
  14. // 用静态代理方式将模型类中的 select() 静态化
  15. public static function select($model, $table, $where = '', $order = '', $limit = '')
  16. {
  17. static::$data = static::$container->make($model)->select($table, $where, $order, $limit);
  18. }
  19. // 用静态代理方式将模型类中的 find() 静态化
  20. public static function find($model, $table, $where = '')
  21. {
  22. static::$data = static::$container->make($model)->find($table, $where);
  23. }
  24. // 用静态代理方式将模型类中的 insert() 静态化
  25. public static function insert($model,$table, $data = [])
  26. {
  27. static::$result = static::$container->make($model)->insert($table,$data);
  28. }
  29. // 用静态代理方式将模型类中的 update() 静态化
  30. public static function update($model,$table, $data = [], $where = '')
  31. {
  32. static::$result = static::$container->make($model)->update($table,$data,$where);
  33. }
  34. // 用静态代理方式将模型类中的 delete() 静态化
  35. public static function delete($model,$table, $where = '')
  36. {
  37. static::$result = static::$container->make($model)->delete($table,$where);
  38. }
  39. // 用静态代理方式将视图类中的 showData() 静态化
  40. public static function showData($view)
  41. {
  42. return static::$container->make($view)->showData(static::$data);
  43. }
  44. // 用静态代理方式将视图类中的 showTable() 静态化
  45. public static function showTable($view)
  46. {
  47. return static::$container->make($view)->showTable(static::$data);
  48. }
  49. // 用静态代理方式将视图类中的 showResult() 静态化
  50. public static function showResult($view)
  51. {
  52. return static::$container->make($view)->showResult(static::$result);
  53. }
  54. }

Controller.php

  1. <?php
  2. namespace goods\controller;
  3. // 控制器类
  4. class Controller
  5. {
  6. // 使用构造方法,自动调用Facade里面的初始化方法
  7. public function __construct(Container $container)
  8. {
  9. Facade::initialize($container);
  10. }
  11. // 查询多条数据
  12. public function select($model, $view, $table, $where = '', $order = '', $limit = '')
  13. {
  14. Facade::select($model, $table, $where, $order, $limit);
  15. return Facade::showTable($view);
  16. }
  17. // 查询一条
  18. public function find($model, $view, $table, $where = '')
  19. {
  20. Facade::find($model, $table, $where);
  21. return Facade::showTable($view);
  22. }
  23. // 查询一条
  24. public function find1($model, $view, $table, $where = '')
  25. {
  26. Facade::find($model, $table, $where);
  27. return Facade::showData($view);
  28. }
  29. // 添加数据
  30. public function insert($model, $view, $table, $data = [])
  31. {
  32. Facade::insert($model, $table, $data);
  33. return Facade::showResult($view);
  34. }
  35. // 更新数据
  36. public function update($model, $view, $table, $data = [], $where = '')
  37. {
  38. Facade::update($model, $table, $data, $where);
  39. return Facade::showResult($view);
  40. }
  41. // 删除数据
  42. public function delete($model, $view, $table, $where = '')
  43. {
  44. Facade::delete($model, $table, $where);
  45. return Facade::showResult($view);
  46. }
  47. }

autoload.php

  1. <?php
  2. namespace goods;
  3. // 类的自动加载器
  4. spl_autoload_register(function ($className){
  5. $path = str_replace('\\', '/', $className);
  6. require dirname(__DIR__) . DIRECTORY_SEPARATOR . $path . '.php';
  7. });

header.php

  1. <?php
  2. namespace goods;
  3. require __DIR__ . '/autoload.php';
  4. use goods\controller\Container;
  5. use goods\controller\Controller;
  6. use goods\model\Goods;
  7. use goods\view\View;
  8. $container = new Container();
  9. $container->bind('goods', function () {
  10. return new Goods();
  11. });
  12. $container->bind('tb', function () {
  13. return new View();
  14. });
  15. $controller = new Controller($container);
  16. ?>

index.php

  1. <?php
  2. require __DIR__ . '/header.php';
  3. ?>
  4. <!doctype html>
  5. <html lang="en">
  6. <head>
  7. <meta charset="UTF-8">
  8. <title>Document</title>
  9. </head>
  10. <body>
  11. <form action="" method="get" style="text-align: center">
  12. <label for="find">请输入要查找的商品ID</label>
  13. <input type="text" id="find" name="find" value="">
  14. <button>查找</button>
  15. <a href="insert.php"><input type="button" name="insert" value="添加"></a>
  16. </form>
  17. </body>
  18. </html>
  19. <?php
  20. // 查找一条数据
  21. if (!empty($_GET['find'])) {
  22. $find = $_GET['find'];
  23. echo $controller->find('goods','tb','goods','id=' . $find);
  24. } else {
  25. echo $controller->select('goods', 'tb', 'goods');
  26. }
  27. // 删除数据
  28. if (!empty($_GET['func']) && $_GET['func'] == 'delete') {
  29. echo $controller->delete('goods','tb','goods','id=' . $_GET['id']);
  30. }

insert.php

  1. <?php
  2. require __DIR__ . '/header.php';
  3. ?>
  4. <!doctype html>
  5. <html lang="en">
  6. <head>
  7. <meta charset="UTF-8">
  8. <title>Document</title>
  9. </head>
  10. <body>
  11. <form method="post">
  12. <p>
  13. <label for="name">商品名称</label>
  14. <input type="text" id="name" name="name" value="" required>
  15. </p>
  16. <p>
  17. <label for="price">商品价格</label>
  18. <input type="text" id="price" name="price" value="" required>
  19. </p>
  20. <p>
  21. <label for="color">商品颜色</label>
  22. <input type="text" id="color" name="color" value="" required>
  23. </p>
  24. <p>
  25. <label for="content">商品描述</label>
  26. <input type="text" id="content" name="content" value="" required>
  27. </p>
  28. <p>
  29. <label for="addtime">添加时间</label>
  30. <input type="date" id="addtime" name="addtime" value="" required>
  31. </p>
  32. <button>添加</button>
  33. <a href="index.php">返回</a>
  34. </form>
  35. </body>
  36. </html>
  37. <?php
  38. $_POST['addtime'] = strtotime($_POST['addtime']);
  39. echo $controller->insert('goods','tb','goods',$_POST);
  40. ?>

update.php

  1. <?php
  2. require __DIR__ . '/header.php';
  3. if (!empty($_GET['id'])) {
  4. $result = $controller->find1('goods', 'tb', 'goods', 'id=' . $_GET['id']);
  5. }
  6. ?>
  7. <!doctype html>
  8. <html lang="en">
  9. <head>
  10. <meta charset="UTF-8">
  11. <title>Document</title>
  12. </head>
  13. <body>
  14. <form method="post">
  15. <p>
  16. <label for="name">商品名称</label>
  17. <input type="text" id="name" name="name" value="<?php echo $result->name;?>" required>
  18. </p>
  19. <p>
  20. <label for="price">商品价格</label>
  21. <input type="text" id="price" name="price" value="<?php echo $result->price;?>" required>
  22. </p>
  23. <p>
  24. <label for="color">商品颜色</label>
  25. <input type="text" id="color" name="color" value="<?php echo $result->color;?>" required>
  26. </p>
  27. <p>
  28. <label for="content">商品描述</label>
  29. <input type="text" id="content" name="content" value="<?php echo $result->content;?>" required>
  30. </p>
  31. <p>
  32. <label for="addtime">添加时间</label>
  33. <input type="date" id="addtime" name="addtime" value="<?php echo $result->addtime;?>" required>
  34. </p>
  35. <button>修改</button>
  36. <a href="index.php">返回</a>
  37. </form>
  38. </body>
  39. </html>
  40. <?php
  41. $_POST['addtime'] = strtotime($_POST['addtime']);
  42. echo $controller->update('goods','tb','goods',$_POST,'id=' . $_GET['id']);
  43. ?>

3. 运行效果

4. 总结

经过了几天努力,总算实现了,虽然很简单,但对MVC有了很深刻的理解。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议