Slim 框架学习,第四天

紧接第三天的内容,今天主要讲解。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框架

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值