# 依賴容器
*****
Slim使用一個可選的依賴項容器來準備、管理和注入應用程序依賴項。Slim支持像PHP-DI一樣實現PSR-11的容器。
Slim uses an optional dependency container to prepare, manage, and inject application dependencies. Slim supports containers that implement[PSR-11](http://www.php-fig.org/psr/psr-11/)like[PHP-DI](http://php-di.org/doc/frameworks/slim.html).
## PHP-DI的示例用法
You don’t*have*to provide a dependency container. If you do, however, you must provide an instance of the container to`AppFactory`before creating an`App`.
您不必提供依賴容器。但是,如果這樣做,則必須在創建 **$app** 之前向`AppFactory`提供容器的實例。
~~~php
<?php
use DI\Container;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
// Create Container using PHP-DI
$container = new Container();
// Set container to create App with on AppFactory
AppFactory::setContainer($container);
$app = AppFactory::create();
~~~
添加一個服務到您的容器:
Add a service to your container:
~~~php
$container->set('myService', function () {
$settings = [...];
return new MyService($settings);
});
~~~
You can fetch services from your container explicitly as well as from inside a Slim application route like this:
你可以顯式地從你的容器中獲取服務,也可以從類似這樣的slim應用程序路由中獲取服務:
~~~php
/**
* Example GET route
*
* @param ServerRequestInterface $request PSR-7 request
* @param ResponseInterface $response PSR-7 response
* @param array $args Route parameters
*
* @return ResponseInterface
*/
$app->get('/foo', function (Request $request, Response $response, $args) {
$myService = $this->get('myService');
// ...do something with $myService...
return $response;
});
~~~
To test if a service exists in the container before using it, use the`has()`method, like this:
要在使用服務之前測試它是否存在于容器中,可以使用`has()`方法,如下所示:
~~~php
/**
* Example GET route
*
* @param ServerRequestInterface $request PSR-7 request
* @param ResponseInterface $response PSR-7 response
* @param array $args Route parameters
*
* @return ResponseInterface
*/
$app->get('/foo', function (Request $request, Response $response, $args) {
if ($this->has('myService')) {
$myService = $this->get('myService');
}
return $response;
});
~~~
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir