首先需要了解什么是依赖注入,在这里我只能copy比较不错的定义如下:
依赖注入(Dependency Injection),组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。依赖注入的目的并非为软件系统带来更多功能,而是为了提升组件重用的频率,并为系统搭建一个灵活、可扩展的平台。(引用:控制反转和依赖注入的理解(通俗易懂))
通过阅读yii2的源码,其中Container类使用di技术实现对类的管理(呵呵~),yii2所支持的对一个类的定义(definition)格式比较丰富:
/**
* Registers a class definition with this container.
*
* For example,
*
* ```php
* // register a class name as is. This can be skipped.
* $container->set('yii\db\Connection');
*
* // register an interface
* // When a class depends on the interface, the corresponding class
* // will be instantiated as the dependent object
* $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
*
* // register an alias name. You can use $container->get('foo')
* // to create an instance of Connection
* $container->set('foo', 'yii\db\Connection');
*
* // register a class with configuration. The configuration
* // will be applied when the class is instantiated by get()
* $container->set('yii\db\Connection', [
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
* 'username' => 'root',
* 'password' => '',
* 'charset' => 'utf8',
* ]);
*
* // register an alias name with class configuration
* // In this case, a "class" element is required to specify the class
* $container->set('db', [
* 'class' => 'yii\db\Connection',
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
* 'username' => 'root',
* 'password' => '',
* 'charset' => 'utf8',
* ]);
*
* // register a PHP callable
* // The callable will be executed when $container->get('db') is called
* $container->set('db', function ($container, $params, $config) {
* return new \yii\db\Connection($config);
* });
* ```
*
*/
所谓类的定义(definition)是指class的类名(yii2中利用命名空间确定类名)。
所谓依赖注入,就是不再通过new Class()去显示的创建一个类的实例(当然不是这么肤浅的目的了),而是定义或者是配置过一次,再次获取该类的实例的时候,仅仅需要某个方法就能实现。