演示代码:
1、model代码
<?php
namespace 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代码
<?php
namespace MVC;
// 引入model和view
require '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(门面技术)是把服务容器中的对象(静态接口)实现静态化访问;