Slim 使用可选的依赖项容器来准备、管理和注入应用程序依赖项。Slim 支持实现 PSR-11 的容器,如 PHP-DI。
您不必提供依赖项容器。但是,如果您提供,您必须在创建 App
之前向 AppFactory
提供容器实例。
<?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();
将服务添加到容器
$container->set('myService', function () {
$settings = [...];
return new MyService($settings);
});
您可以从容器中明确获取服务,也可以像下面这样从 Slim 应用程序路由内部获取服务
/**
* 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;
});
在使用服务之前测试该服务是否存在于容器中,使用 has()
方法,如下所示
/**
* 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;
});
如果您想使用容器中已定义的依赖项创建 App
,可以使用 AppFactory::createFromContainer()
方法。
示例
<?php
use App\Factory\MyResponseFactory;
use DI\Container;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Slim\Factory\AppFactory;
require_once __DIR__ . '/../vendor/autoload.php';
// Create Container using PHP-DI
$container = new Container();
// Add custom response factory
$container->set(ResponseFactoryInterface::class, function (ContainerInterface $container) {
return new MyResponseFactory(...);
});
// Configure the application via container
$app = AppFactory::createFromContainer($container);
// ...
$app->run();
受支持的 App
依赖项是