批改状态:合格
老师批语:
作业标题:0823mvc架构模式思想
作业内容:1. mvc之间的关系并用代码演绎? 2. 你理解的容器与依赖注入? 3. 什么是facade门面, 有什么作用?
mvc之间的关系并用代码演绎?
Model
用于建立数据库连接,为控制器(Controller)提供底层数据
<?phpnamespace mvc_demo;use PDO;class Model{public function getData(){return (new PDO('mysql:host=localhost;dbname=info','root','root',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_WARNING]))->query('SELECT `id`,`gender`,`uname`,`create_time` FROM `user` order by id asc LIMIT 11')->fetchAll(PDO::FETCH_ASSOC);}public function editData(){}}
<?phpnamespace mvc_demo;// require 'Model.php';class View {public function fetch($data){$table = '<table >';$table.='<caption>用户信息表</caption>';$table.= '<tr align="center"><td>编号</td><td>姓名</td><td>性别</td><td>创建时间</td><td>操作</td></tr>';foreach($data as $user){$user['gender'] = $user['gender'] == 1 ?'男' : '女';$table.='<tr>';$table.='<td>'.$user['id'].'</td>';$table.='<td>'.$user['uname'].'</td>';$table.='<td>'.$user['gender'].'</td>';$table.='<td>'.date("Y-m-d H:m:s",$user['create_time']).'</td>';$table.='<td><button>删除</button> <button>编辑</button> </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:lightblue;}td,th {border: 1px solid; padding:5px}</style>';
<?phpclass 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);}public function edit(){$this->model->editData();}}$model = new Model;$view = new View;$c = new Controller($model,$view);echo $c->index();

你理解的容器与依赖注入?
容器 container 依赖注入的类统一由容器进行管理,容器 数组 如果当前类依赖的对象很多, 可以将这些依赖的对象 , 类,闭包,放到一个”服务容器”中进行统一管理 bind make
什么是facade门面, 有什么作用?
facade 门面为容器中的(动态)类提供了一个静态调用接口,相比于传统的静态方法调用, 带来了更好的可测试性和扩展性。facade就是在服务容器和控制器之间加了一个中间层
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号