Skip to content

依赖容器

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

使用 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';

// 使用 PHP-DI 创建容器
$container = new Container();

// 设置容器以在 AppFactory 上创建 App
AppFactory::setContainer($container);
$app = AppFactory::create();

向容器添加一个服务:

$container->set('myService', function () {
    $settings = [...];
    return new MyService($settings);
});

您既可以明确地从容器中获取服务,也可以在 Slim 应用程序路由内部这样做:

/**
 * 示例 GET 路由
 *
 * @param  ServerRequestInterface $request  PSR-7 请求
 * @param  ResponseInterface      $response  PSR-7 响应
 * @param  array                  $args 路由参数
 *
 * @return ResponseInterface
 */
$app->get('/foo', function (Request $request, Response $response, $args) {
    $myService = $this->get('myService');

    // ...使用 $myService 做一些操作...

    return $response;
});

要在使用服务之前检查容器中是否存在该服务,请使用 has() 方法,例如:

/**
 * 示例 GET 路由
 *
 * @param  ServerRequestInterface $request  PSR-7 请求
 * @param  ResponseInterface      $response  PSR-7 响应
 * @param  array                  $args 路由参数
 *
 * @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';

// 使用 PHP-DI 创建容器
$container = new Container();

// 添加自定义的响应工厂
$container->set(ResponseFactoryInterface::class, function (ContainerInterface $container) {
    return new MyResponseFactory(...);
});

// 通过容器配置应用程序
$app = AppFactory::createFromContainer($container);

// ...

$app->run();

支持的 App 依赖项有:

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