摘要:通過本章的學(xué)習(xí),了解了如果通過依賴注入實現(xiàn)解耦,并通過外觀模式實現(xiàn)數(shù)據(jù)的接口統(tǒng)一,讓更多的業(yè)務(wù)方法在業(yè)務(wù)類中實現(xiàn),避免了原先客戶端訪問需要了解實際調(diào)用業(yè)務(wù)的問題。實現(xiàn)代碼如下:Db.php:<?php namespace app\model\index\login; //數(shù)據(jù)庫操作類 class Db { //數(shù)據(jù)庫連
通過本章的學(xué)習(xí),了解了如果通過依賴注入實現(xiàn)解耦,并通過外觀模式實現(xiàn)數(shù)據(jù)的接口統(tǒng)一,讓更多的業(yè)務(wù)方法在業(yè)務(wù)類中實現(xiàn),避免了原先客戶端訪問需要了解實際調(diào)用業(yè)務(wù)的問題。實現(xiàn)代碼如下:
Db.php:
<?php namespace app\model\index\login; //數(shù)據(jù)庫操作類 class Db { //數(shù)據(jù)庫連接 public function connect() { return '數(shù)據(jù)庫連接成功<br>'; } }
Validate.php:
<?php namespace app\model\index\login; //數(shù)據(jù)驗證類 class Validate { //數(shù)據(jù)驗證 public function check() { return '數(shù)據(jù)驗證成功<br>'; } }
View.php
<?php namespace app\model\index\login; //視圖圖 class View { //內(nèi)容輸出 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; } //創(chuàng)建類 public function make($abstract,$pams=[]) { return call_user_func_array($this->instance[$abstract],$pams); } }
Facade.php
<?php namespace app\model\index\login; class Facade { //創(chuàng)建容器變量 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(); }); } //連接數(shù)據(jù)庫 public static function connect() { return static::$container->make('db')->connect(); } //驗證數(shù)據(jù) public static function check() { return static::$container->make('validate')->check(); } //顯示數(shù)據(jù) 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() { //創(chuàng)建容器 $container = new Container(); //初始化容器 Facade::init($container); //登錄 Facade::login(); } }
效果圖:
批改老師:韋小寶批改時間:2019-02-26 10:01:41
老師總結(jié):寫的很不錯 這些都是框架中的一些重要知識點 當(dāng)然也可以使用在其他的地方 沒事要記得多去研究研究