Slim v3使用依赖容器去准备,管理和注入应用的依赖。Slim的依赖容器是Container-Interop 接口的实现。你可以使用Slim内置的容器(基于Pimple)也可以使用第三方库去替换,例如Acclimate 或者 PHP-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() 魔术方法来添加容器中不存在的属性值。

必须的服务

Slim 容器__必须__实现了这些服务。如果你使用内置的容器,这些都已经实现了。如果要使用第三方的容器,__必须__实现下面的服务。

Settings

应用中的Settings 服务数组中包含下面的键:httpVersion, outputBuffering, responseChunkSize 和 determineRouteBeforeAppMiddleware

environment

实现 \Slim\Interfaces\Http\EnvironmentInterface接口

request

实现 \Psr\Http\Message\ServerRequestInterface 接口

response

实现 \Psr\Http\Message\ResponseInterface接口

router

实现 \Slim\Interfaces\RouterInterface接口

foundHandler

实现 \Slim\Interfaces\InvocationStrategyInterface接口

errorHandler

应用发生错误的时候调用。必须返回实现 `\Psr\Http\Message\ResponseInterface`的实例 并且 接受三个参数:

1. \Psr\Http\Message\ServerRequestInterface
2. \Psr\Http\Message\ResponseInterface
3. \Exception

notFoundHandler

在HTTP 请求 URI无法匹配应用中的路由的时候调用。必须返回实现 `\Psr\Http\Message\ResponseInterface` 的实例,并且接受两个参数:
1. \Psr\Http\Message\ServerRequestInterface
2. \Psr\Http\Message\ResponseInterface

notAllowedHandler

在应用路由可以匹配到当前的HTTP请求URI,但是并没有它的方法时候调用。必须返回实现 `\Psr\Http\Message\ResponseInterface` 的实例,并且接受三个参数:
1. \Psr\Http\Message\ServerRequestInterface
2. \Psr\Http\Message\ResponseInterface
3. Array of allowed HTTP methods (存储允许的方法的数组)

callableResolver

实现 \Slim\Interfaces\CallableResolverInterface接口


文档翻译的并不是很专业,仅供个人学习作用,建议看官方文档。

如有兴趣,请看下一篇 SLIM 3 文档(七)-请求(REQUEST)