Control inversion and Dependency injection

Source: Internet
Author: User

Dependency Injection is a design pattern in PHP programming and is designed to reduce coupling and improve maintainability.

Problem phenomenon: We often encounter a class in the programming process to instantiate another class, this class is instantiated another class, this layer of package form, often let us modify the code at the time, modified once, related to the upper layer will also be modified, if the hierarchical relationship is more complex, this modification is catastrophic. Workaround:
In order to solve the above problems, some people put forward a concept, can let the upper layer only define the interface, and the lower layer to implement the interface, this becomes the upper layer of dependency, this concept is called the dependency inversion principle (DIP), this strategy will reduce the coupling degree, improve availability, One way to achieve this is the inversion of control (IOC), which simply says that the idea of a control reversal is that the class is not instantiated in this class for the class on which it is dependent, all by a third party to instantiate it, and then by a property or class constructor to pass an instance into the original, which is the method of dependency injection (DI), This third party is the control reversal container, if this third party is a service loader then this is called the Services locator, this is also the implementation of control inversion. Summarize:
Dependency injection is one of the specific methods for controlling inversion, which is to implement the dependency inversion principle, and to solve the dependency coupling of upper class to the lower class and improve the usability. Description: In various frameworks of PHP, the control inversion container is implemented for the dependency injection to provide third-party classes for easy programming. The following example takes the YII2.0.4 framework as an example. Example: // 为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赋值为Examples of Excelfile public function init() { $this->_excelExt = new ExcelFile() }   // 当需要的时候调用excelfile类 public function doSomething() { $this->_excelExt->OutExcel(); } }Now here are two questions 1, if you modify the Excelfile class, modify the relevant method name, parameter, return, and so on, then the corresponding stock class also need to make changes, and whoever calls the stock class DoSomething, will be affected, and then the next layer? Is it catastrophic to change? 2, if one day you do not want to export to Excel, or you want to let Excel and PDF format are supported, in addition to the careful modification of dosomething and its upper calling method, there is no other way? The method is to rely on injection, the class used by the stock is passed to it except Excelfile, it is only used, the modification operation is done in a third party, and the stock has no relation, there are two methods of passing, attribute passing or constructor passing, here the pass you can also call inject // 属性注入 class Stock extend yii\db\ActiveRecord { private $_excelExt;   // 为了方便类实例的注入,这里定义了Set方法,在yii里这里会转化为Set魔术方法 public function setEmailSender($value) { $this->_excelExt = $value; }   // Call the Excelfile class when needed 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;Generate PDF files $comment 1->dosomething(); // 这是构造函数注入的例子 class Stock extend yii\db\ActiveRecord { Private $_excelext;   // 构造函数注入 public function __construct($filer) { $this->_excelExt = $filer; }   // Call the Excelfile class when needed public function afterInsert() { $this->_excelext->outexcel (); } }   $Exceler = new ExcelFile(); $Pdfer = new PdfFile();   // 用构造函数注入 $comment1 = new Comment($Exceler); // 用构造函数r注入 $comment2 = new Comment($Pdfer);In this way, the class association is decoupled by injection, and all dependent classes are instantiated out-of-class, which is the nature of dependency injection, and in Yii there is a specially provided class to instantiate dependencies, called di containers, and dependency injection containers use yii\di\Container;   // 创建一个DI容器 $container = new Container; // 为UserLister定义一个别名 $container->set(‘excel‘, ‘app\ExcelFile‘);   // 获取这个UserList的实例 $lister = $container->get(‘excel‘);

 

Control inversion and Dependency injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.