# 依賴容器(Dependency Container)
Slim 使用依賴容器來準備、管理和注入應用程序的相關依賴。Slim 支持 [Container-Interop](https://github.com/container-interop/container-interop) 接口實現的容器。你可以使用 Slim 的內置容器(基于 [Pimple](http://pimple.sensiolabs.org/))或者第三方的容器,比如 [Acclimate](https://github.com/jeremeamia/acclimate-container) 或 [PHP-DI](http://php-di.org/)。
## 如何使用容器
你并不_必須_提供一個依賴容器。如果你提供了,那么,你必須注入此容器的實例到 Slim 應用程序的構造函數中。
```
$container = new \Slim\Container;
$app = new \Slim\App($container);
```
你可以顯式或隱式地從依賴容器中獲取服務。你可以像下面這樣子從 Slim 應用程序的路由中獲取一個顯示的容器實例。
```
/**
* Example GET route
*
* @param \Psr\Http\Message\ServerRequestInterface $req PSR7 request
* @param \Psr\Http\Message\ResponseInterface $res PSR7 response
* @param array $args Route parameters
*
* @return \Psr\Http\Message\ResponseInterface
*/
$app->get('/foo', function ($req, $res, $args) {
$myService = $this->get('myService');
return $res;
});
```
你可以這樣隱式地從容器中取得服務:
```
/**
* Example GET route
*
* @param \Psr\Http\Message\ServerRequestInterface $req PSR7 request
* @param \Psr\Http\Message\ResponseInterface $res PSR7 response
* @param array $args Route parameters
*
* @return \Psr\Http\Message\ResponseInterface
*/
$app->get('/foo', function ($req, $res, $args) {
$myService = $this->myService;
return $res;
});
```
Slim uses `__get()` and `__isset()` magic methods that defer to the application’s container for all properties that do not already exist on the application instance.
## 必需的服務
你的容器必須實現這些必需的服務。如果你使用的是 Slim 內置的容器,這些服務都是已經準備好了的。如果你選擇使用第三方容器,那么你必須自己來實現這些服務。
settings
應用程序設置項的關聯數組(Associative array),包括以下關鍵字:
* `httpVersion`
* `responseChunkSize`
* `outputBuffering`
* `determineRouteBeforeAppMiddleware`.
* `displayErrorDetails`.
environment
`\Slim\Interfaces\Http\EnvironmentInterface` 的實例.
request
`\Psr\Http\Message\ServerRequestInterface`的實例.
response
`\Psr\Http\Message\ResponseInterface`的實例.
router
`\Slim\Interfaces\RouterInterface`的實例.
foundHandler
`\Slim\Interfaces\InvocationStrategyInterface` 的實例.
phpErrorHandler
PHP 7 錯誤被拋出時調用的 Callable。這個 callable **必須**返回一個 `\Psr\Http\Message\ResponseInterface` 的實例,并接收三個參數:
1. `\Psr\Http\Message\ServerRequestInterface`
2. `\Psr\Http\Message\ResponseInterface`
3. `\Error`
errorHandler
拋出異常時調用的 Callable。這個 callable **必須**返回一個 `\Psr\Http\Message\ResponseInterface` 的實例,并接收三個參數:
1. `\Psr\Http\Message\ServerRequestInterface`
2. `\Psr\Http\Message\ResponseInterface`
3. `\Exception`
notFoundHandler
如果當前的 HTTP 請求 URI 未能匹配到應用程序路由,則調用這個 Callable。這個 callable **必須**返回一個 `\Psr\Http\Message\ResponseInterface` 的實例,并接收三個參數:
1. `\Psr\Http\Message\ServerRequestInterface`
2. `\Psr\Http\Message\ResponseInterface`
notAllowedHandler
如果一個應用程序路由匹配到當前 HTTP 請求的路徑而不是它的方法,則調用這個 Callable。這個 callable **必須** 返回一個 `\Psr\Http\Message\ResponseInterface` 的實例并接收三個參數:
1. `\Psr\Http\Message\ServerRequestInterface`
2. `\Psr\Http\Message\ResponseInterface`
3. Array of allowed HTTP methods
callableResolver
`\Slim\Interfaces\CallableResolverInterface` 的實例.