Correction status:Uncorrected
Teacher's comments:
依赖注入案例
<?php require_once 'Model.php'; require_once 'View.php'; class Controller { protected $View = null; protected $Model = null; public function __construct(Model $Model,View $View) { $this->view = $View; $this->model = $Model; } public function index(){ $data = $this->model->getData(); return $this->view->fetch($data); } } $View = new View(); $Model = new Model(); $controller = new Controller($Model,$View); echo $controller->index();
点击 "运行实例" 按钮查看在线实例
容器案例
<?php require_once 'Model.php'; require_once 'View.php'; class Container { protected $instance = []; public function bind($lee,Closure $process){ $this->instance[$lee] = $process; } public function make($lee,$params=[]){ return call_user_func_array($this->instance[$lee],[]); } } $container = new Container(); $container->bind('model',function (){return new Model();}); $container->bind('view',function (){return new View();}); class Controller { public function index(Container $container){ $data = $container->make('model')->getData(); return $container->make('view')->fetch($data); } } $controller = new Controller(); echo $controller->index($container);
点击 "运行实例" 按钮查看在线实例
Facade 案例
<?php require_once 'Model.php'; require_once 'View.php'; class Container { protected $instance = []; public function bind($lee,Closure $process){ $this->instance[$lee] = $process; } public function make($lee,$params=[]){ return call_user_func_array($this->instance[$lee],[]); } } $container = new Container(); $container->bind('model',function (){return new Model();}); $container->bind('view',function (){return new View();}); class Facade { protected static $container = null; protected static $data = []; public static function initialize(Container $container){ static::$container = $container; } public static function getData(){ static::$data = static::$container->make('model')->getData(); } public static function fetch(){ return static::$container->make('view')->fetch(static::$data); } } class Student extends Facade { } class Controller { public function __construct(Container $container){ Student::initialize($container); } public function index(){ Student::getData(); return Student::fetch(); } } $controller = new Controller($container); echo $controller->index();
点击 "运行实例" 按钮查看在线实例
总结,越做越复杂!