通过本章的学习,了解了如果通过依赖注入实现解耦,并通过外观模式实现数据的接口统一,让更多的业务方法在业务类中实现,避免了原先客户端访问需要了解实际调用业务的问题。实现代码如下:
Db.php:
<?php namespace app\model\index\login; //数据库操作类 class Db { //数据库连接 public function connect() { return '数据库连接成功<br>'; } }
Validate.php:
<?php namespace app\model\index\login; //数据验证类 class Validate { //数据验证 public function check() { return '数据验证成功<br>'; } }
View.php
<?php namespace app\model\index\login; //视图图 class View { //内容输出 public function display() { return '用户登录成功'; } }
Container.php
<?php namespace app\model\index\login; class Container { //用户存放传入的类 public $instance=[]; //绑定类 public function bind($abstract,\Closure $closure) { $this->instance[$abstract]=$closure; } //创建类 public function make($abstract,$pams=[]) { return call_user_func_array($this->instance[$abstract],$pams); } }
Facade.php
<?php namespace app\model\index\login; class Facade { //创建容器变量 public static $container; //初始化容器 public static function init(Container $container) { static::$container=$container; //将Db类绑定到容器中 static::$container->bind('db', function(){ return new Db(); }); //将Validate类实例绑定到容器中 static::$container->bind('validate', function(){ return new Validate(); }); //将View类实例绑定到容器中 static::$container->bind('view', function(){ return new View(); }); } //连接数据库 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')->display(); } //登录 public static function login() { echo self::connect(); echo self::check(); echo self::display(); } }
Index.php
<?php namespace app\index\controller; use app\model\index\login\Container; use app\model\index\login\Facade; use think\Db; use think\Request; class Index { public function index() { //创建容器 $container = new Container(); //初始化容器 Facade::init($container); //登录 Facade::login(); } }
效果图: