Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:慢慢接触到了设计模式, 也慢慢接触了实际项目开发了
<?php
namespace mvc;
// 模型类用于数据库操作
class Model
{
public function getdata()
{
return (new \PDO("mysql:host=php.cn;dbname=php",'root','root'))
->query("SELECT * FROM `staff` LIMIT 5")->fetchAll(\PDO::FETCH_ASSOC);
}
}
// print_r((new Model)->gertdata());
<?php
namespace mvc;
// 视图类用于渲染数据
class View
{
public function fetch($date)
{
$table .= '<table>';
$table .= '<caption>员工信息<caption>';
$table .= ' <tr><td>工号</td><td>状态</td><td>部门</td><td>职务</td><td>性别</td></tr>';
foreach($date as $date1){
$table .= '<tr>';
$table .= '<td>' . $date1['id'] . '</td>';
$table .= '<td>' . $date1['state'] . '</td>';
$table .= '<td>' . $date1['section'] . '</td>';
$table .= '<td>' . $date1['duty'] . '</td>';
$table .= '<td>' . $date1['gender'] . '</td>';
$table .= '<tr>';
}
$table .= '</table>';
return $table;
}
}
echo '<style>
table {border-collapse: collapse; border: 1px solid;text-align: center; width: 500px;height: 150px;width: 600px;}
caption {font-size: 1.2rem; margin-bottom: 10px;}
tr:first-of-type { background-color:wheat;}
td,th {border: 1px solid; padding:5px}
</style>';
// require 'mvc_model.php';
// echo (new view)->fetch((new Model)->getdata());
<?php
namespace mvc;
// 控制器
require 'mvc_model.php';
require 'mvc_view.php';
class Controller
{
public function index()
{
$model = new Model;
$date = $model->getdata();
$view = new View;
return $view->fetch($date);
}
}
// 客户端
// 实例化控制器类
$controller = new Controller;
echo $controller->index();
<?php
namespace mvc;
// 控制器
require 'mvc_model.php';
require 'mvc_view.php';
class Controller
{
public function index(model $model,view $view)
{
$date = $model->getdata();
return $view->fetch($date);
}
}
// 依赖注入方法1:把实列化的过程放在客户端进行实现,通过参数的方式传递给控制器中方法
$model =new model;
$view = new view;
// 客户端
// 实例化控制器类
$controller = new Controller;
echo $controller->index($model,$view);
<?php
namespace mvc;
// 控制器
require 'mvc_model.php';
require 'mvc_view.php';
class Controller
{
public $model;
public $view;
public function __construct($model,$view)
{
$this->model = $model;
$this->view = $view;
}
public function index()
{
$date = ($this->model)->getdata();
return ($this->view)->fetch($date);
}
}
// 依赖注入方法2:通过创建构造方法的方式,初始化参数,供多个方法调用
$model =new model;
$view = new view;
// 客户端
// 实例化控制器类
$controller = new Controller($model,$view);
echo $controller->index();