紧接第三天的内容,今天主要讲解。index.php 中的,$app->run() 做了些什么
我们先看一下 run 方法:
public function run($silent = false)
{
$response = $this->container->get('response'); //得到Slim\Http\Response 对象
try {
ob_start(); //ob_start()函数用于打开缓冲区。PHP代码的数据块和echo()输出都会进入缓冲区而不会立刻输出
$response = $this->process($this->container->get('request'), $response);
} catch (InvalidMethodException $e) {
$response = $this->processInvalidMethod($e->getRequest(), $response);
} finally {
$output = ob_get_clean();
}
if (!empty($output) && $response->getBody()->isWritable()) {
$outputBuffering = $this->container->get('settings')['outputBuffering'];
if ($outputBuffering === 'prepend') {
// prepend output buffer content
$body = new Http\Body(fopen('php://temp', 'r+'));
$body->write($output . $response->getBody());
$response = $response->withBody($body);
} elseif ($outputBuffering === 'append') {
// append output buffer content
$response->getBody()->write($output);
}
}
$response = $this->finalize($response);//设置 header 中的 content-length
if (!$silent) {
$this->respond($response);
}
return $response;
}
这里面有几个点需要注意下:
1. $response = $this->process($this->container->get('request'), $response);
2. $response = $this->finalize($response);//设置 header 中的 content-length
其实run 方法的逻辑很清楚
- 先获取一个response 对象
- 先使用ob_start()打开缓冲区,不输出到浏览器
- 然后设置response 的各个属性,如 header 信息 ,body信息等等
- 最后输出到浏览器即可
如果有疑问,可以打开run开头的 response 和 末尾的 response 做对比就好,就很清楚的看到,中间的过程做了些什么。
结束语:
从第一天到,第四天。我们大致了解了一下 Slim 框架页面的生命周期,离完全掌握它,还有很多的路要走。
接下来,将会具体的点上去讲Slim框架。如 容器,依赖注入的实现,router 类,response类,request 类的实现,来进一步掌握Slim框架