依赖容器(Dependency Container)

未完整翻译

Slim 使用依赖容器来准备、管理和注入应用程序的相关依赖。Slim 支持 Container-Interop 接口实现的容器。你可以使用 Slim 的内置容器(基于 Pimple)或者第三方的容器,比如 AcclimatePHP-DI

如何使用容器

你并不必须提供一个依赖容器。如果你提供了,那么,你必须注入此容器的实例到 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 使用 __get()__isset() 魔术方法,按照应用程序容器 that defer to the application’s container for all properties that do not already exist on the application instance.尚未存在于应用程序实例中的所有属性。

必需的服务

你的容器必须实现这些必需的服务。如果你使用的是 Slim 内置的容器,这些服务都是已经准备好了的。如果你选择使用第三方容器,那么你必须自己来实现这些服务。

settings
Associative array of application settings, including keys httpVersion, outputBuffering, responseChunkSize and determineRouteBeforeAppMiddleware.
environment
Instance of \Slim\Interfaces\Http\EnvironmentInterface.
request
Instance of \Psr\Http\Message\ServerRequestInterface.
response
Instance of \Psr\Http\Message\ResponseInterface.
router
Instance of \Slim\Interfaces\RouterInterface.
foundHandler
Instance of \Slim\Interfaces\InvocationStrategyInterface.
errorHandler
Callable invoked if application error. The callable MUST return an instance of \Psr\Http\Message\ResponseInterface and accept three arguments:
  1. \Psr\Http\Message\ServerRequestInterface
  2. \Psr\Http\Message\ResponseInterface
  3. \Exception
notFoundHandler
Callable invoked if the current HTTP request URI does not match an application route. The callable MUST return an instance of \Psr\Http\Message\ResponseInterface and accept two arguments:
  1. \Psr\Http\Message\ServerRequestInterface
  2. \Psr\Http\Message\ResponseInterface
notAllowedHandler
Callable invoked if an application route matches the current HTTP request path but not its method. The callable MUST return an instance of \Psr\Http\Message\ResponseInterface and accept three arguments:
  1. \Psr\Http\Message\ServerRequestInterface
  2. \Psr\Http\Message\ResponseInterface
  3. Array of allowed HTTP methods
callableResolver
Instance of \Slim\Interfaces\CallableResolverInterface.