# 開始
歡迎!這份指南將幫助你在項目中使用PHP-DI.
在開始之前,你需要知道什么是[依賴注入](understanding-di.md).
如果你不知道,這一整篇文章就是為了它: 了解依賴注入.
## 安裝
Install PHP-DI with [Composer](http://getcomposer.org/doc/00-intro.md):
```
composer require php-di/php-di
```
PHP-DI 需要 PHP 5.5以上版本.
## 基礎應用
### 1. 使用依賴注入
第一,讓我們寫使用依賴注入的代碼而不用其考慮PHP-DI
```php
class Mailer
{
public function mail($recipient, $content)
{
// send an email to the recipient
}
}
```
```php
class UserManager
{
private $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
public function register($email, $password)
{
// The user just registered, we create his account
// ...
// We send him an email to say hello!
$this->mailer->mail($email, 'Hello and welcome!');
}
}
```
像我們看到的,`UserManager`使用`Mailer`作為構造函數的參數: 這就是依賴注入!
### 2. 創建容器
你可以使用一個容器的實例去讓開發更簡單一些:
```php
$container = DI\ContainerBuilder::buildDevContainer();
```
如果你想使用定義文件(下面會解釋)或者調整一些配置,你可以使用容器構造器.
```php
$builder = new DI\ContainerBuilder();
$builder->...
$container = $builder->build();
```
### 3. 創建對象
不用PHP-DI,我們將必須"引導"相關依賴像這樣:
```php
$mailer = new Mailer();
$userManager = new UserManager($mailer);
```
取而代之的,我們能讓PHP-DI來解決依賴:
```php
$userManager = $container->get('UserManager');
```
在這個場景下,PHP-DI將創建一個Mailer對象和UserManager對象
> 它怎么知道如何去注入?
這個容器使用一個叫做自動**autowiring**的技術,這不是PHP-DI獨創的,但是它仍然非場好用.它將掃描代碼并查看那些參數在參數在構造函數里.明知一些
在我們的例子中,`UserManager`的構造函數使用了`Mailer`對象: PHP-DI 知道他需要創建一個.很簡單,而且非常有效率.
> 等等, 像這樣奇怪的掃描代碼沒有風險么?
不用擔心,PHP-DI使用[PHP的反射類](http://php.net/manual/en/book.reflection.php)是非常標準的: Laravel, Zend Framework 和其他很多容器也是這么做的,這些信息只讀一次然后緩存下來,不會有任何影響.
## 注入定義
我們已經看過**autowiring**,像PHP-DI自動計算出依賴類這種.但是我們有三種方法去定義怎么去注入類:
- using [autowiring](autowiring.md)
- using [annotations](annotations.md)
- using [PHP definitions](php-definitions.md)
隨意使用任何一種,這里有一個PHP定義的文件
```php
return [
'api.url' => 'http://api.example.com',
'Webservice' => function (Container $c) {
return new Webservice($c->get('api.url'));
},
'Controller' => DI\object()
->constructor(DI\get('Webservice')),
];
```
請閱讀[依賴定義](definition.md)文檔去了解 autowiring, annotations and PHP definitions.
## 框架中使用
我們已經在上面看了一個使用容器獲得對象的例子:
```php
$userManager = $container->get('UserManager');
```
我們經常不希望在應用中任何地方都需要調用容器,他將使**我們的代碼綁定到容器**.這就是大家知道的*服務定位模式*
*待繼續*