批改状态:合格
老师批语:容器, 门面, 都是对类成中的高度抽象和封装, 目标就是和用户提供一个简单方便的访问接口
1、model代码
<?phpnamespace MVC;// use PDO;class Model{protected $dsn;protected $username;protected $password;protected static $db=null;public function __construct($dsn,$username,$password){$this->dsn=$dsn;$this->username=$username;$this->password=$password;self::$db=new \PDO($this->dsn,$this->username,$this->password);}public function select($limit,$num){$sql="select * FROM `staffs` LIMIT {$limit} OFFSET {$num}";$res=self::$db->query($sql);return $res->fetchAll(\PDO::FETCH_ASSOC);}}
2、view代码(略)
3、control代码
<?phpnamespace MVC;// 引入model和viewrequire 'Model.php';require 'View.php';// 准备数据库连接参数$dsn='mysql:host=php.edu;dbname=php.edu;charset=utf8;port=3306';$username='phpedu';$password='123456';// 服务容器class Container{protected $class_container=[];public function bind($class,\Closure $obj){$this->class_container[$class]=$obj;}public function make($class,$params=[]){return call_user_func_array($this->class_container[$class],$params);}}$container=new Container;$container->bind('model',function()use($dsn,$username,$password){return new Model($dsn,$username,$password);});$container->bind('view',function (){return new View();});// 控制类(外部model和view对象注入)/*class Control{protected $model;protected $view;public function __construct(Model $model,View $view){$this->model=$model;$this->view=$view;}public function html($n,$m){$data=$this->model->select($n,$m);return $this->view->index($data);}}$model=new Model($dsn,$username,$password);$view=new View();echo (new Control($model,$view))->html(5,10);*/// 控制类,面向服务容器的形式class Control{public function html(Container $container,$n,$m){$data=$container->make('model')->select($n,$m);return $container->make('view')->index($data);}}echo (new Control())->html($container,10,10);
4、control类门面技术:
//定义门面类class Facades{public static $class=null;public static $data=[];public static function class(Container $container){static::$class=$container;}}//模型类静态接口class Model1 extends Facades{public static function getdata($n,$m){static::$data=static::$class->make('model')->select($n,$m);}}//视图类静态接口class View1 extends Facades{public static function index($data){return static::$data=static::$class->make('view')->index($data);}}//控制类class Control{ protected $container;public function __construct(Container $container){$this->container=$container;Facades::class($this->container);}public function html($n,$m){Model1::getdata($n,$m);return View1::index(Facades::$data);}//自动销毁服务容器public function __destruct(){$this->container=null;}}//客户端代码,匿名类使用完自动销毁echo (new Control($container))->html(12,10);
5、演示结果:
1、call_user_func_array():利用回调函数处理数组
2、MVC是一个经典的:数据,视图,控制器分离的代码组织方法;
3、服务容器类:把所有需要实列化的类统一交给一个类来管理;
4、facades(门面技术)是把服务容器中的对象(静态接口)实现静态化访问;
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号