Correction status:qualified
Teacher's comments:依赖注入的原理与本质并没有总结
1、模型类Model.php
<?php /** * 模型类:用于数据库操作,数据访问 */ //require __DIR__ . '\inc\connect.php'; class Model { public function getData(){ $dsn = 'mysql:host=127.0.0.1;dbname=vmall'; $uname = 'root'; $pw = ''; $sql = "SELECT `pro_id`, `name`, `price`, `num` FROM `product` LIMIT 5"; $pdo = new PDO($dsn, $uname, $pw,array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8")); $stmt = $pdo->prepare($sql); $stmt->execute(); $result = $stmt -> fetchAll(PDO::FETCH_ASSOC); // print_r($result);die; return $result; } public function getData2(){ $sql = "SELECT `pro_id`, `name`, `price`, `num` FROM `product` LIMIT 5"; $stmt = $pdo->prepare($sql); $stmt->execute(); $result = $stmt -> fetchAll(PDO::FETCH_ASSOC); print_r($result);die; return $result; } }
2、视图类:渲染数据 View.php
<?php // 视图类:渲染数据 class View { public function fetch($data) { $table = '<table border="1" cellspacing="0" cellpadding="3" width="400">'; $table .= '<caption>商品信息表</caption>'; $table .= '<tr bgcolor="#add8e6"><th>ID</th><th>品名</th><th>价格</th><th>数量</th></tr>'; // 遍历模型数据 foreach ($data as $pro){ $table .= '<tr>'; $table .= '<td>' . $pro['pro_id'] . '</td>'; $table .= '<td>' . $pro['name'] . '</td>'; $table .= '<td>' . $pro['price'] . '</td>'; $table .= '<td>' . $pro['num'] . '</td>'; $table .= '</tr>'; } $table .= '</$table>'; return $table; } }
3、控制器3:依赖注入,解决了对象之间的高度耦合问题
<?php // 控制器3:依赖注入,解决了对象之间的高度耦合问题 // 加载模型类、视图类 require 'Model.php'; require 'View.php'; // 控制器类 class Controller { protected $model; protected $view; // 注入点是一个构造方法 public function __construct(Model $model, View $view) { $this->model = $model; $this->view = $view; } public function index() { // 1、获取数据 $data = $this->model->getData(); // 2、渲染模板 return $this ->view->fetch($data); } } // 客户端调用 $model = new Model(); $view = new View(); $controller = new Controller($model, $view); echo $controller->index();
显示效果: