Correction status:qualified
Teacher's comments:
注入让类之间解耦,解耦后通过参数传入类的实例,而不是在某个类内部实例化其他类。代码修改更加方便。
容器注入是在注入的前提下,通过容器管理各个依赖类,保存在关联数组中。类和相应的实例化方法绑定bind,
实例化参数传入容器完成实例化,make.
Facade 方便了调用,都采用静态调用。Facade中调用Container中的make 方法,完成各个类的实例化。
container.php
<?php class Db { public function connect() { return 'connect db success<br>'; } } class Validate { public function check() { return 'validate success<br>'; } } class View { public function login() { return 'login success <br>'; } } // 创建容器类 class Container { public $instance=[]; // 类名与实例化方法绑定 public function bind($abstract,Closure $process) { $this->instance[$abstract]=$process; } public function make($abstrct,$params=[]) { return call_user_func_array($this->instance[$abstrct],$params); } } $container=new Container(); $container->bind('db',function(){ return new DB(); }); $container->bind('validate',function(){ return new Validate(); }); $container->bind('view',function(){ return new View(); });
点击 "运行实例" 按钮查看在线实例
demo.php
<?php require 'container.php'; class Facade { protected static $container=null; public static function initialize(Container $container) { static::$container=$container; } public static function connect() { return static::$container->make('db')->connect(); } public static function check() { return static::$container->make('validate')->check(); } public static function display() { return static::$container->make('view')->login(); } } Facade::initialize($container); echo Facade::connect(); echo Facade::check(); echo Facade::display();
点击 "运行实例" 按钮查看在线实例