博客列表 >PHP视图控制器MVC基本认识

PHP视图控制器MVC基本认识

阿心
阿心原创
2020年05月17日 10:30:06683浏览

模型类:model.php

  1. <?php
  2. class Model
  3. {
  4. public function getData()
  5. {
  6. require $_SERVER['DOCUMENT_ROOT'].'/config/connect.php';
  7. $sql="SELECT * FROM `user` LIMIT 10";
  8. $stmt = $pdo->prepare($sql);
  9. $stmt->execute();
  10. $user = $stmt->fetchAll(PDO::FETCH_ASSOC);
  11. return $user;
  12. // print_r($users);
  13. }
  14. }
  15. ?>
  16. <html>
  17. <head>
  18. <body>
  19. <style>
  20. table {border-collapse: collapse; border: 1px solid;text-align: center; width: 500px;height: 150px;width: 600px;}
  21. caption {font-size: 1.2rem; margin-bottom: 10px;}
  22. tr:first-of-type { background-color:wheat;}
  23. td,th {border: 1px solid; padding:5px}
  24. </style>
  25. </body>
  26. </head>
  27. </html>

视图类:View.php

  1. <?php
  2. class View
  3. {
  4. public function fetch($data)
  5. {
  6. $table='<table>';
  7. $table.='<caption>用户列表</caption>';
  8. $table.='<tr><th>id</th><th>账户</th><th>姓名</th><th>tel</th><th>存款</th></tr>';
  9. foreach($data as $user) {
  10. $table .= '<tr>';
  11. $table .= '<td>' . $user['id'] . '</td>';
  12. $table .= '<td>' . $user['account'] . '</td>';
  13. $table .= '<td>' . $user['username'] . '</td>';
  14. $table .= '<td>' . $user['phone'] . '</td>';
  15. $table .= '<td>' . $user['money'] . '</td>';
  16. $table .= '</tr>';
  17. }
  18. $table.='</table>';
  19. return $table;
  20. }
  21. }

控制器一,demo.php

  1. <?php
  2. require 'Model.php';
  3. require 'View.php';
  4. //创建控制 方法一:
  5. class controller
  6. {
  7. public function index()
  8. {
  9. $m=new Model;
  10. //print_r($m->getData());
  11. $data=$m->getData();
  12. $v=new View;
  13. $res=$v->fetch($data);
  14. return $res;
  15. }
  16. }
  17. $controller=new controller;
  18. echo $controller->index();

控制方法二,demo1.php

  1. <?php
  2. require 'model.php';
  3. require 'view.php';
  4. //创建控制 方法二:
  5. class controller1
  6. {
  7. public function index($m,$v){
  8. //获取数据
  9. $data=$m->getData();
  10. //渲染视图
  11. return $v->fetch($data);
  12. }
  13. }
  14. $m=new Model;
  15. $v=new View;
  16. $controller1=new controller1;
  17. $res=$controller1->index($m,$v);
  18. echo $res;

控制方法三,demo2.php

  1. <?php
  2. require 'model.php';
  3. require 'view.php';
  4. class controller2
  5. {
  6. //依赖对象属性
  7. private $m;
  8. private $v;
  9. public function __construct(Model $m, View $v)
  10. {
  11. $this->m = $m;
  12. $this->v = $v;
  13. }
  14. public function index()
  15. {
  16. $data = $this->m->getData();
  17. return $this->v->fetch($data);
  18. }
  19. }
  20. $m = new Model;
  21. $v = new View;
  22. $controller2 = new controller2($m,$v);
  23. echo $controller2->index();

总结:MVC基本认识大概思路有了。还需要认真多抄几遍估计可以加深下认识。

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