依赖容器

Slim 使用可选的依赖容器来准备、管理和注入应用程序依赖项。Slim 支持像PHP-DI这样实现PSR-11 的容器。

使用 PHP-DI 的示例

您不必提供依赖项容器。但是,如果这样做,则必须AppFactory在创建App.

<?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依赖项是:

  • Psr\Http\Message\ResponseFactoryInterface
  • Slim\Interfaces\CallableResolverInterface
  • Slim\Interfaces\RouteCollectorInterface
  • Slim\Interfaces\RouteResolverInterface
  • Slim\Interfaces\MiddlewareDispatcherInterface