vitepress-blog/src/laravel/渲染页面.md
2024-07-09 20:01:02 +08:00

82 lines
2.2 KiB
Markdown

---
title: 渲染页面
---
## 渲染页面
```php
$response = $kernel->handle(
$request = Request::capture()
)->send();
```
这里只需要分析这一行代码,它将请求对象`Request::capture()`捕获,并将其传递给内核对象`$kernel->handle()`,然后将响应对象返回。
在`Laravel`中,`Request::capture()`方法会捕获当前的请求对象
### send()方法
`$response`是类`Symfony\Component\HttpFoundation\Response`实例,在该类中可以找到`send()`方法。
```php
public function send()
{
// 发送http响应头
$this->sendHeaders();
// 发送http响应内容
$this->sendContent();
if (\function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} elseif (\function_exists('litespeed_finish_request')) {
litespeed_finish_request();
} elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
static::closeOutputBuffers(0, true);
flush();
}
return $this;
}
```
#### sendHeaders()方法
当类`Symfony\Component\HttpFoundation\Response`实例化时,构造函数详细
```php
public function __construct(?string $content = '', int $status = 200, array $headers = [])
{
$this->headers = new ResponseHeaderBag($headers);
$this->setContent($content);
$this->setStatusCode($status);
$this->setProtocolVersion('1.0');
}
public function sendHeaders()
{
// headers have already been sent by the developer
if (headers_sent()) {
return $this;
}
// 这里设置返回的响应头
foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
$replace = 0 === strcasecmp($name, 'Content-Type');
foreach ($values as $value) {
header($name.': '.$value, $replace, $this->statusCode);
}
}
// cookies
foreach ($this->headers->getCookies() as $cookie) {
header('Set-Cookie: '.$cookie, false, $this->statusCode);
}
// status
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
return $this;
}
```
#### sendContent()方法
```php
public function sendContent()
{
echo $this->content;
return $this;
}
```