批改状态:合格
老师批语:mvc是一种编程思想 , 并非设计 模式, 这点要注意
<?phpnamespace 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);}}
<?phpnamespace 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>';
<?phpnamespace 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();

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号