
批改狀態(tài):合格
老師批語(yǔ):
在服務(wù)容器與工作類之間添加一個(gè)中間層,門面
namespace mvc;
use Closure;
// 加載模型和視圖
require 'model.php';
require 'view.php';
// 服務(wù)容器
class Container1{
//對(duì)象容器
protected $instances=[];
// 添加對(duì)象
public function bind($alias,Closure $process){
$this->instances[$alias]=$process;
}
// 取出對(duì)象
public function make($alias,$params=[]){
return call_user_func_array($this->instances[$alias],[]);
}
}
// 將依賴的外部對(duì)象添加到容器中
$container=new Container1();
$container->bind('model',function(){return new Model();});
$container->bind('view',function(){return new View();});
//--------------------
// 在服務(wù)容器與工作類之間添加一個(gè)中間層,門面
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
{
//構(gòu)造器主要是為了facade門面的初始化
public function __construct(Container1 $container)
{
Facade::initialize($container);
}
public function index()
{
$data = UsersModel::getData();
return UsersView::fetch($data);
}
}
// 客戶端測(cè)試
$controller = new Controller5($container);
echo $controller->index();
調(diào)用代碼更加簡(jiǎn)潔,使用方便且減少出錯(cuò)
中文網(wǎng): https://www.phpcomposer.com/
官網(wǎng)下載: https://getcomposer.org/composer.phar
創(chuàng)建 composer.bat:@php "%~dp0composer.phar" %*
php composer.phar -V
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)