标签:
依赖注入是php编程中的一种设计模式,其目的也是为了降低耦合度,提高可维护性。
// 为Excel定义一个接口类interface ExcelInterface{ public function OutExcel(...);} // 定义Excel文件生成类class ExcelFile implements ExcelInterface{ // 实现生成excel文件的方法 public function OutExcel(){}} // 这是库存AR类class Stock extend yii\db\ActiveRecord{ private $_excelExt; // 将$_excelExt赋值为ExcelFile的实例 public function init() { $this->_excelExt = new ExcelFile() } // 当需要的时候调用excelfile类 public function doSomething() { $this->_excelExt->OutExcel(); }}// 属性注入class Stock extend yii\db\ActiveRecord{ private $_excelExt; // 为了方便类实例的注入,这里定义了Set方法,在yii里这里会转化为Set魔术方法 public function setEmailSender($value) { $this->_excelExt = $value; } // 当需要的时候调用excelfile类 public function doSomething() {$this->_excelExt->OutExcel(); }} $Exceler = new ExcelFile();$Pdfer = new PdfFile(); $comment1 = new Stock;// 使用属性注入$comment1->excelExt = $Exceler;// 生成excel文件$comment1->doSomething(); $comment2 = new Stock;// 使用属性注入$comment2->excelExt = $Pdfer;// 这是构造函数注入的例子class Stock extend yii\db\ActiveRecord{ private $_excelExt; // 构造函数注入 public function __construct($filer) { $this->_excelExt = $filer; } // 当需要的时候调用excelfile类 public function afterInsert() {$this->_excelExt->OutExcel(); }} $Exceler = new ExcelFile();$Pdfer = new PdfFile(); // 用构造函数注入$comment1 = new Comment($Exceler);// 用构造函数r注入$comment2 = new Comment($Pdfer);use yii\di\Container; // 创建一个DI容器$container = new Container;// 为UserLister定义一个别名$container->set(‘excel‘, ‘app\ExcelFile‘); // 获取这个UserList的实例$lister = $container->get(‘excel‘);
标签:
原文地址:http://www.cnblogs.com/phpinfo/p/4592252.html