Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:mvc是一种编程思想 , 并非设计 模式, 这点要注意
<?php
namespace mvc_demo1;
//模型类:数据库操作
class Model{
public function getData()
{
return (new \PDO('mysql:host=localhost;dbname=phpedu;','root','root'))
->query('SELECT * FROM `user` LIMIT 10')
->fetchAll(\PDO::FETCH_ASSOC);
}
}
<?php
namespace mvc_demo1;
//视图类
class View
{
public function fetch($data)
{
$table = '<table>';
$table .= '<caption>员工信息表</caption>';
$table .= '<tr><th>ID</th><th>姓名</th><th>性别</th><th>职务</th><th>手机号</th><th>入职时间</th></tr>';
// 将数据循环遍历出来
foreach ($data as $staff) {
$table .= '<tr>';
$table .= '<td>' . $staff['id'] . '</td>';
$table .= '<td>' . $staff['name'] . '</td>';
$table .= '<td>' . ($staff['sex'] ? '男' : '女') . '</td>';
$table .= '<td>' . $staff['position'] . '</td>';
$table .= '<td>' . $staff['mobile'] . '</td>';
$table .= '<td>' . date('Y年m月d日', $staff['hiredate']) . '</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>';
<?php
namespace mvc_demo2;
// 控制器依赖注入点改到构造方法, 实现对外部依赖对象的共享
// 1. 加载模型类
require 'Model.php';
use mvc_demo1\Model as M;
// 2. 加载视图
require 'View.php';
use mvc_demo1\View as V;
// 3. 服务容器
class Container
{
//对象容器
protected $instances = [];
//绑定:向对象容器中添加一个类实例
public function bind($alias, \Closure $process)
{
$this->instances[$alias] = $process;
}
//取出:从容器中取出一个类实例(new)
public function make($alias, $params = [])
{
return call_user_func_array($this->instances[$alias],[]);
}
}
// 客户端
$container = new Container();
// 实例化控制器类
$container->bind('model',function() {return new M;});
$container->bind('view',function () {return new V;});
//////////////////////////////////////////////
// 4. Facade门面技术: 可以接管对容器中的对象的访问
class Facade
{
//容器实例属性
protected static $container = null;
//初始化方法:从外部接受一个依赖对象:服务容器实例
public static function initialize(Container $container)
{
static::$container = $container;
}
}
class Model extends Facade
{
public static function getData()
{
return static::$container->make('model')->getData();
}
}
class View extends Facade
{
public static function fetch($data)
{
return static::$container->make('view')->fetch($data);
}
}
//////////////////////////////////////////////
// 3. 创建控制器
class Controller
{
//构造方法:调用门面的初始化方法
public function __construct(Container $container)
{
Facade::initialize($container);
}
public function index()
{
//1.获取数据
$data = Model::getData();
//2.渲染模板
return View::fetch($data);
}
}
//实例化控制器类
$controller = new Controller($container);
echo $controller->index();