<?php//命名空间namespace mvctest;//定义一个模型类:用来获取数据class Model {public function getData() {return (new \PDO('mysql:host=localhost;dbname=genbackmanasys', 'root', 'root'))->query('SELECT * FROM `user_info`')->fetchAll(\PDO::FETCH_ASSOC);}}//调试代码//print_r((new Model)->getData());
<?php//命名空间namespace mvctest;//定义一个视图类:用来渲染数据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><th>城市</th><th>个性签名</th><th>注册时间</th></tr>';//将数据循环遍历出来foreach ($data as $staff) {$table.='<tr>';$table.='<td>' . $staff['id'] . '</td>';$table.='<td>' . $staff['user_name'] . '</td>';$table.='<td>' . $staff['sex'] . '</td>';$table.='<td>' . $staff['position'] . '</td>';$table.='<td>' . $staff['email'] . '</td>';$table.='<td>' . $staff['cphone_n'] . '</td>';$table.='<td>' . $staff['city'] . '</td>';$table.='<td>' . $staff['signature'] . '</td>';$table.='<td>' . date('Y年m月d日', $staff['reg_time']) . '</td>';$table.='<tr>';}$table .= '</table>';return $table;}}//定义样式echo '<style>table {border-collapse: collapse;border: 1px solid;}th, td{border: 1px solid; padding: 5px;}</style>';//调试代码//require 'Model.php';//echo (new View)->fetch((new Model)->getData());
<?php//命名空间namespace mvctest;// 1. 加载模型类require 'Model.php';// 2. 加载视图类require 'View.php';// 3. 创建服务容器类:统一管理类实例class Container {// 1. 创建对象容器protected $box = [];// 2. 创建绑定方法:向对象容器中添加一个类实例public function bind($var, \Closure $process) {//对象容器中的键是对象名,值是其实例化过程$this->box[$var] = $process;}// 3. 创建取出方法:从容器中取出一个类实例(new的过程)public function make($var, $params = []) {//用回调方式返回一个对象return call_user_func_array($this->box[$var], []);}}// 4. 创建门面类:接管对容器对象的访问class Facade {//创建一个容器,用来保存外部对象protected static $container = null;//创建一个容器,用来保存实例属性protected static $data = [];//初始化方法:从外部接受一个依赖对象,该对象为服务容器的实例public static function initialize(Container $container){//初始化容器实例属性static::$container = $container;}}//模型成员静态化class Model1 extends Facade {//以静态方法访问的方式获取数据public static function getData() {static::$data = static::$container->make('model')->getData();}}//视图成员静态化class View1 extends Facade {//以静态方法访问的方式返回视图public static function fetch() {return static::$data = static::$container->make('view')->fetch(static::$data);}}// 5. 创建控制器类:将用户请求和数据进行关联/绑定class Controller {//构造方法:调用门面的初始化方法public function __construct(Container $container){Facade::initialize($container);}public function bind() {// 1. 获取数据Model1::getData();// 2. 渲染模板/视图return View1::fetch();}}//客户端代码// 1. 创建服务容器$container = new Container;// 2. 绑定$container->bind('model', function() {return new Model;});$container->bind('view', function() {return new View;});// 3. 实例化控制器类$controller = new Controller($container);echo $controller->bind();

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