Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
在服务容器与工作类之间添加一个中间层,门面
namespace mvc;
use Closure;
// 加载模型和视图
require 'model.php';
require 'view.php';
// 服务容器
class Container1{
//对象容器
protected $instances=[];
// 添加对象
public function bind($alias,Closure $process){
$this->instances[$alias]=$process;
}
// 取出对象
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 Facade{
protected static $container =null;
//初始化
public static function initialize(Container1 $container){
static::$container=$container;
}
}
class UsersModel extends Facade{
public static function getData(){
return static::$container->make('model')->getData();
}
}
class UsersView extends Facade{
public static function fetch($data){
return static::$container->make('view')->fetch($data);
}
}
//--------------------
class Controller5
{
//构造器主要是为了facade门面的初始化
public function __construct(Container1 $container)
{
Facade::initialize($container);
}
public function index()
{
$data = UsersModel::getData();
return UsersView::fetch($data);
}
}
// 客户端测试
$controller = new Controller5($container);
echo $controller->index();
调用代码更加简洁,使用方便且减少出错
中文网: https://www.phpcomposer.com/
创建 composer.bat:@php "%~dp0composer.phar" %*
php composer.phar -V
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/