批改状态:合格
老师批语:一二阶段作业,请在6月10日前完成
一、服务容器:container服务容器,是把容器简单的看成一个全局变量,并用关联数组把字符串和构造函数做绑定,轻松解决控制器的耦合度的相关问题。如以下代码:
<?php
namespace mvc_demo;
require 'Model.php';
require 'View.php';
// 创建服务容器
class Container1
{
// 创建对象容器
protected $instances = [];
// 绑定: 向对象容器中添加一个类实例(类实例的别名alias)
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 Container1;
// 绑定
$container->bind('model', function () {return new Model;});
$container->bind('view', function () {return new View;});
//创建控制器
class Controller4
{
public function index(Container1 $container)
{
// 1. 获取数据
$data = $container->make('model')->getData();
// 2. 渲染模板/视图
return $container->make('view')->fetch($data);
}
}
// 客户端
// 实例化控制器类
$controller = new Controller4();
echo $controller->index($container);
//追加销毁
unset($controller);
echo '销毁了';
echo '<hr>';model.php
<?php
namespace mvc_demo;
// 模型类: 用于数据库操作
class Model
{
public function getData()
{
return (new \PDO('mysql:host=localhost;dbname=aaa', 'aaa','123456'))
->query('SELECT * FROM `staffs` LIMIT 10')
->fetchAll(\PDO::FETCH_ASSOC);
}
}view.php
<?php
namespace mvc_demo;
// 视图类
class View
{
public function fetch($data)
{
$table = '<table>';
$table .= '<caption>员工信息表</caption>';
$table .= '<tr><th>ID</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>' . 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>';输出结果:

二、学习总结:一知半解~_~查了一下资料:
container是一个简单的服务容器里面有bind,make两个方法:bind是向容器中绑定服务对象。make则是从容器中取出对象。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号