Blogger Information
Blog 36
fans 2
comment 0
visits 23560
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
12月06号:小型MVC框架
Rambo-Yang
Original
794 people have browsed it

文件结构

Db.php

  1. namespace mvc;
  2. use PDO;
  3. session_start();
  4. ini_set('date.timezone','Asia/Shanghai');
  5. class Db
  6. {
  7. //数据库配置信息
  8. private $dbConfig = [
  9. 'db' => 'mysql',
  10. 'host' => 'localhost',
  11. 'username' => 'root',
  12. 'password' => 'root',
  13. 'dbname' => 'mvc',
  14. ];
  15. //新增主键id
  16. public static $insertId = null;
  17. //受影响的记录数量
  18. public static $num = 0;
  19. //数据库的连接
  20. private static $pdo = null;
  21. //构造方法接收参数
  22. private function __construct(...$params)
  23. {
  24. $dsn = "{$this->dbConfig['db']}:host={$this->dbConfig['host']};dbname={$this->dbConfig['dbname']}";
  25. $username = "{$this->dbConfig['username']}";
  26. $password = "{$this->dbConfig['password']}";
  27. try {
  28. self::$pdo = new PDO($dsn, $username, $password);
  29. } catch (\PDOException $e) {
  30. die('数据库连接失败:' . $e->getMessage());
  31. }
  32. }
  33. //单例模式判断连接
  34. public static function connect(...$params)
  35. {
  36. // 如果没有实例化 就实例化,已经实例化就返回
  37. if (is_null(self::$pdo)){
  38. new self(...$params);
  39. }
  40. return self::$pdo;
  41. }
  42. //禁止外部访问克隆方法
  43. private function __clone()
  44. {
  45. }
  46. // 新增,更新,删除操作
  47. public static function exec($sql)
  48. {
  49. $stmt = self::$pdo->prepare($sql);
  50. $stmt->execute();
  51. if ($stmt->rowCount()>0){
  52. //如果是新增操作,初始化新增主键id属性
  53. if(null !==self::$pdo->lastInsertId()){
  54. self::$insertId = self::$pdo->lastInsertId();
  55. }
  56. self::$num = $stmt->rowCount(); //返回受影响的记录数量
  57. }else {
  58. $error = self::$pdo->errorInfo(); //获取最后操作的错误信息的数组
  59. //[0]错误标识符[1]错误代码[2]错误信息
  60. print '操作失败'.$error[0].':'.$error[1].':'.$error[2];
  61. }
  62. }
  63. //获取单条数据
  64. public static function fetch($sql)
  65. {
  66. $stmt = self::$pdo->prepare($sql);
  67. $stmt->execute();
  68. return $stmt->fetch(PDO::FETCH_ASSOC);
  69. }
  70. //获取多条数据
  71. public static function fetchAll($sql)
  72. {
  73. $stmt = self::$pdo->prepare($sql);
  74. $stmt->execute();
  75. return $stmt->fetchAll(PDO::FETCH_ASSOC);
  76. }
  77. }

Model.php

  1. namespace mvc;
  2. require 'Db.php';
  3. class Model
  4. {
  5. public $data = null;
  6. //链接数据库
  7. public function __construct()
  8. {
  9. Db::connect();
  10. }
  11. //获取单条数据
  12. public function get($id)
  13. {
  14. $sql = "SELECT * FROM `users` WHERE id = {$id}";
  15. $this->data = Db::fetch($sql);
  16. return $this->data;
  17. }
  18. // 获取多条数据
  19. public function getAll()
  20. {
  21. $sql = "SELECT * FROM `users` WHERE `status` = 1";
  22. $this->data = Db::fetchAll($sql);
  23. return $this->data;
  24. }
  25. //删除单条数据
  26. public function del($id)
  27. {
  28. $sql = "UPDATE `users` SET `status` = 0 WHERE id = {$id}";
  29. $this->data = Db::exec($sql);
  30. return $this->data;
  31. }
  32. }

Controller.php

  1. //控制器
  2. namespace mvc;
  3. require './model/Model.php';
  4. require './view/View.php';
  5. //服务容器
  6. class Container
  7. {
  8. // 创建容器数组,存放实例方法
  9. public $int = null;
  10. //放进去,将类实例化过程绑定到容器
  11. public function bind($alias, \Closure $process)
  12. {
  13. $this->int[$alias] = $process;
  14. }
  15. //取出来,执行容器中的实例方法
  16. public function make($alias, $params = [])
  17. {
  18. //
  19. return call_user_func_array($this->int[$alias], $params);
  20. }
  21. }
  22. $container = new Container();
  23. $container->bind('model', function () {return new Model();});
  24. $container->bind('view', function () {return new View();});
  25. //门面模式
  26. class Facade
  27. {
  28. //接收实例化容器
  29. protected static $container = null;
  30. //绑定数据
  31. protected static $data;
  32. protected static $id;
  33. //用服务容器给它初始化, 将容器注入
  34. public static function initialize(Container $container)
  35. {
  36. static::$container = $container;
  37. }
  38. //将模型中的方法静态化
  39. public static function getAll()
  40. {
  41. static::$data = static::$container->make('model')->getAll();
  42. }
  43. //将模型中的方法静态化--查询单条数据
  44. public static function get($id)
  45. {
  46. static::$id = static::$container->make('model')->get($id);
  47. }
  48. //将模型中的方法静态化--删除单条数据
  49. public static function del($id)
  50. {
  51. static::$id = static::$container->make('model')->del($id);
  52. }
  53. //将模型中的方法静态化--更新数据
  54. public static function update($sql)
  55. {
  56. static::$id = static::$container->make('model')->del($sql);
  57. }
  58. //将视图中的方法静态化
  59. public static function fetch()
  60. {
  61. return static::$container->make('view')->fetch(static::$data);
  62. }
  63. //将视图中的方法静态化--单条数据
  64. public static function find()
  65. {
  66. return static::$container->make('view')->find(static::$id);
  67. }
  68. //将视图中的方法静态化--删除单条数据
  69. public static function del1()
  70. {
  71. return static::$container->make('view')->del1(static::$id);
  72. }
  73. }
  74. //创建控制器
  75. class Controller
  76. {
  77. //初始化,调用 Facade里面的初始化方法
  78. public function __construct(Container $container)
  79. {
  80. Facade::initialize($container);
  81. }
  82. //调用单条数据
  83. public function find($id='')
  84. {
  85. $id = isset($_GET['id']) ? $_GET['id'] : $id;
  86. if (empty($id)){
  87. die('非法操作');
  88. }
  89. //获取数据
  90. Facade::get($id);
  91. //渲染模板
  92. return Facade::find();
  93. }
  94. //调用全部数据
  95. public function getAll()
  96. {
  97. Facade::getAll();
  98. return Facade::fetch();
  99. }
  100. //删除单条数据
  101. public function del1($id='')
  102. {
  103. if(@$_SESSION['name'] != 'admin'){
  104. echo '<script>alert("你不是管理员不能删除数据");history.back();</script>';
  105. exit();
  106. }
  107. $id = isset($_GET['id']) ? $_GET['id'] : $id;
  108. if (empty($id)){
  109. die('非法操作');
  110. }
  111. Facade::del($id);
  112. return Facade::del1();
  113. }
  114. //登录
  115. public function login()
  116. {
  117. require dirname(__DIR__).'/'.'login.php';
  118. }
  119. //验证登录
  120. public function check()
  121. {
  122. require dirname(__DIR__).'/'.'check.php';
  123. }
  124. //退出登录
  125. public function logout()
  126. {
  127. require dirname(__DIR__).'/'.'logout.php';
  128. }
  129. }
  130. $controller = new Controller($container);

View.php

  1. //视图:渲染数据
  2. namespace mvc;
  3. class View
  4. {
  5. //获取所有数据
  6. public function fetch($data)
  7. {
  8. $table = '<table align="center" cellpadding="10">';
  9. $table .= '<caption>学生信息表</caption>';
  10. $table .= '<tr><th>ID</th><th>姓名</th><th>性别</th><th>爱好</th><th>录入时间</th><th>操作</th></tr>';
  11. foreach ($data as $item){
  12. $item['sex'] = $item['sex']==1 ? '男' : '女';
  13. $item['entry_time'] = date('Y-m-d H:i:s',$item['entry_time']);
  14. $table .='<tr>';
  15. $table .='<td>'. $item['id'].'</td>';
  16. $table .='<td>'. $item['name'].'</td>';
  17. $table .='<td>'. $item['sex'] . '</td>';
  18. $table .='<td>'. $item['hobby'].'</td>';
  19. $table .='<td>'. $item['entry_time'].'</td>';
  20. $table .='<td><a href="?a=find&id=' . $item['id'] . '">详细 </a><a href="?a=del1&id=' . $item['id'] . '"> 删除</a></td>';
  21. $table .= '</tr>';
  22. }
  23. $table .= '</table>';
  24. $table .= '<p align="center">共计 ' . count($data). ' 条数据</p> ';
  25. return $table;
  26. }
  27. //获取单条数据
  28. public function find($data)
  29. {
  30. $table = '<table align="center" cellpadding="10">';
  31. $table .= '<caption>学生信息表</caption>';
  32. $table .= '<tr><th>ID</th><th>姓名</th><th>性别</th><th>手机</th>
  33. <th>爱好</th><th>生日</th><th>录入时间</th><th>状态</th></tr>';
  34. $data['sex'] = $data['sex']==1 ? '男' : '女';
  35. $data['entry_time'] = date('Y-m-d H:i:s',$data['entry_time']);
  36. $data['status'] = $data['status']==1 ? '正常' : '已删除';
  37. $table .='<tr>';
  38. $table .='<td>'. $data['id'].'</td>';
  39. $table .='<td>'. $data['name'].'</td>';
  40. $table .='<td>'. $data['sex'] . '</td>';
  41. $table .='<td>'. $data['tel'].'</td>';
  42. $table .='<td>'. $data['hobby'].'</td>';
  43. $table .='<td>'. $data['birthday'].'</td>';
  44. $table .='<td>'. $data['entry_time'].'</td>';
  45. $table .='<td>'. $data['status'].'</td>';
  46. $table .= '</tr>';
  47. $table .= '</table>';
  48. return $table;
  49. }
  50. //删除单条数据
  51. public function del1($data)
  52. {
  53. return '成功删除了' .Db::$num. '条数据';
  54. }
  55. }
  56. echo '<style>
  57. a { text-decoration: none; color: #333;}
  58. table a:first-of-type{ color: red}
  59. table {border-collapse: collapse; border: 1px solid; width: 60%; text-align: center }
  60. caption {font-size: 1.2rem; margin-bottom: 10px;}
  61. tr:first-of-type { background-color:lightblue;}
  62. td,th {border: 1px solid}
  63. td:first-of-type {text-align: center}
  64. </style>';

index.php

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  6. <title>首页</title>
  7. <style>
  8. body {
  9. text-align: center
  10. }
  11. nav {
  12. width: 60%;
  13. margin: 20px auto;
  14. height: 40px;
  15. background: #444;
  16. line-height: 40px;
  17. padding: 0 20px;
  18. }
  19. nav a {
  20. font-size: 16px;
  21. color: #fff;
  22. padding: 0 10px;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <?php
  28. require 'controller/Controller.php';
  29. ?>
  30. <nav><a href="/">首页</a>
  31. <?php if (isset($_SESSION['name'])) {
  32. echo '<a >' . $_SESSION['name'] . '</a><a href="index.php?a=logout">退出</a>';
  33. } else {
  34. echo '<a href="index.php?a=login">登录</a>';
  35. } ?>
  36. </nav>
  37. <?php
  38. //获取方法
  39. $a = isset($_GET['a']) ? $_GET['a'] : 'getAll';
  40. //执行控制器方法
  41. echo $controller->$a();
  42. ?>
  43. </body>
  44. </html>

login.php

  1. <?php
  2. if(isset($_SESSION['name'])){
  3. echo '<script>alert("你已登录,请不要重复登录");location.assign("index.php");</script>';
  4. }
  5. ?>
  6. <h2>用户登陆</h2>
  7. <form action="index.php?a=check" method="post">
  8. <p>
  9. 用户名:<input type="text" name="name">
  10. </p><p>
  11. 密码:<input type="password" name="pwd">
  12. </p>
  13. <p>
  14. <input type="submit" value="提交">
  15. </p>
  16. </form>

check.php

  1. namespace mvc;
  2. //print_r($_SERVER);
  3. if ($_SERVER['REQUEST_METHOD'] === 'POST'){
  4. $name = $_POST['name'];
  5. $pwd = md5($_POST['pwd']);
  6. Db::connect();
  7. $sql = "SELECT * FROM `admin` WHERE `username` = '{$name}' AND `password` = '{$pwd}'";
  8. $user = Db::fetch($sql);
  9. if(false === $user){
  10. echo '<script>alert("账号或密码错误");history.back();</script>';
  11. die();
  12. }
  13. $_SESSION['name'] = $user['username'];
  14. echo '<script>alert("登录成功");location.assign("index.php");</script>';
  15. exit();
  16. }else{
  17. die("非法操作");
  18. }

logout.php

  1. if(isset($_SESSION['name'])){
  2. session_destroy();
  3. echo '<script>alert("退出成功");location.assign("index.php");</script>';
  4. }else{
  5. echo '<script>alert("请先登录");location.assign("login.php");</script>';
  6. // echo '<script>alert("请先登录");location.assign("login.php");</script>';
  7. }

总结

  • 又看了几遍老师录的从零开始开发框架,模仿着写,总算跑起来了。写的很乱,很lower,修改数据和添加数据传参没有思路,还不知道怎么下手。
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:我录的那个教程, 对于你们来说, 实在是太简单了, 你应该向更高目标发起挑战
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post