导读:今天继续学习Slim/Route.php 类剩余的功能。前面的章节,已经对每个方法都说过了。今天只剩一个__invoke 方法了
__invoke
/**
* 根据当前请求和响应对象 调用 能调用的路由
* Dispatch route callable against current Request and Response objects
*
* 该方法调用可调用的路由对象。
* 如果为路由注册了中间件,则每个可调用的中间件,将被按顺序调用
* This method invokes the route object's callable. If middleware is
* registered for the route, each callable middleware is invoked in
* the order specified.
*
* @param ServerRequestInterface $request The current Request object
* @param ResponseInterface $response The current Response object
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception if the route callable throws an exception
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
{
//这里得到的是容器的闭包对象
/**
* object(Closure)#19 (2) {
["this"]=>
object(Slim\Container)#3 (7) {
["defaultSettings":"Slim\Container":private]=>
array(7) {
["httpVersion"]=>
string(3) "1.1"
["responseChunkSize"]=>
int(4096)
["outputBuffering"]=>
string(6) "append"
["determineRouteBeforeAppMiddleware"]=>
bool(false)
["displayErrorDetails"]=>
bool(false)
["addContentLengthHeader"]=>
bool(true)
["routerCacheFile"]=>
bool(false)
}
**/
$this->callable = $this->resolveCallable($this->callable);
/** @var InvocationStrategyInterface $handler */
/**
* ["foundHandler"]=>
object(Closure)#12 (1) {
["this"]=>
object(Slim\DefaultServicesProvider)#7 (0) {
}
}
*/
$handler = isset($this->container) ? $this->container->get('foundHandler') : new RequestResponse();
$newResponse = $handler($this->callable, $request, $response, $this->arguments);
if ($newResponse instanceof ResponseInterface) {
// if route callback returns a ResponseInterface, then use it
$response = $newResponse;
} elseif (is_string($newResponse)) {
// if route callback returns a string, then append it to the response
if ($response->getBody()->isWritable()) {
$response->getBody()->write($newResponse);
}
}
return $response;
}
下面看一下,最后返回的对象
object(Slim\Http\Response)#26 (5) {
["status":protected]=>
int(200)
["reasonPhrase":protected]=>
string(0) ""
["protocolVersion":protected]=>
string(3) "1.1"
["headers":protected]=>
object(Slim\Http\Headers)#27 (1) {
["data":protected]=>
array(1) {
["content-type"]=>
array(2) {
["value"]=>
array(1) {
[0]=>
string(24) "text/html; charset=UTF-8"
}
["originalKey"]=>
string(12) "Content-Type"
}
}
}
["body":protected]=>
object(Slim\Http\Body)#25 (7) {
["stream":protected]=>
resource(37) of type (stream)
["meta":protected]=>
array(6) {
["wrapper_type"]=>
string(3) "PHP"
["stream_type"]=>
string(4) "TEMP"
["mode"]=>
string(3) "w+b"
["unread_bytes"]=>
int(0)
["seekable"]=>
bool(true)
["uri"]=>
string(10) "php://temp"
}
["readable":protected]=>
NULL
["writable":protected]=>
bool(true)
["seekable":protected]=>
NULL
["size":protected]=>
NULL
["isPipe":protected]=>
NULL
}
}
最终返回的是 Slim\Http\Response 对象
至此,该类就学完了