前面兩節我們分別講了Laravel的控制器和Request對象,在講Request對象的那一節我們看了Request對象是如何被創建出來的以及它支持的方法都定義在哪里,講控制器時我們詳細地描述了如何找到Request對應的控制器方法然后執行處理程序的,本節我們就來說剩下的那一部分,控制器方法的執行結果是如何被轉換成響應對象Response然后返回給客戶端的。
創建Response讓我們回到Laravel執行路由處理程序返回響應的代碼塊:
namespace Illuminate/Routing;html' target='_blank'>class Router implements RegistrarContract, BindingRegistrar protected function runRoute(Request $request, Route $route) $request- setRouteResolver(function () use ($route) { return $route; $this- events- dispatch(new Events/RouteMatched($route, $request)); return $this- prepareResponse($request, $this- runRouteWithinStack($route, $request) protected function runRouteWithinStack(Route $route, Request $request) $shouldSkipMiddleware = $this- container- bound( middleware.disable ) $this- container- make( middleware.disable ) === true; //收集路由和控制器里應用的中間件 $middleware = $shouldSkipMiddleware ? [] : $this- gatherRouteMiddleware($route); return (new Pipeline($this- container)) - send($request) - through($middleware) - then(function ($request) use ($route) { return $this- prepareResponse( $request, $route- run()}
在講控制器的那一節里我們已經提到過runRouteWithinStack方法里是最終執行路由處理程序(控制器方法或者閉包處理程序)的地方,通過上面的代碼我們也可以看到執行的結果會傳遞給Router的prepareResponse方法,當程序流返回到runRoute里后又執行了一次prepareResponse方法得到了要返回給客戶端的Response對象, 下面我們就來詳細看一下prepareResponse方法。
class Router implements RegistrarContract, BindingRegistrar * 通過給定值創建Response對象 * @param /Symfony/Component/HttpFoundation/Request $request * @param mixed $response * @return /Illuminate/Http/Response|/Illuminate/Http/JsonResponse public function prepareResponse($request, $response) return static::toResponse($request, $response); public static function toResponse($request, $response) if ($response instanceof Responsable) { $response = $response- toResponse($request); if ($response instanceof PsrResponseInterface) { $response = (new HttpFoundationFactory)- createResponse($response); } elseif (! $response instanceof SymfonyResponse ($response instanceof Arrayable || $response instanceof Jsonable || $response instanceof ArrayObject || $response instanceof JsonSerializable || is_array($response))) { $response = new JsonResponse($response); } elseif (! $response instanceof SymfonyResponse) { $response = new Response($response); if ($response- getStatusCode() === Response::HTTP_NOT_MODIFIED) { $response- setNotModified(); return $response- prepare($request);}
在上面的代碼中我們看到有三種Response:
Class NameRepresentationPsrResponseInterface(PsrHttpMessageResponseInterface的別名)Psr規范中對服務端響應的定義IlluminateHttpJsonResponse (SymfonyComponentHttpFoundationResponse的子類)Laravel中對服務端JSON響應的定義IlluminateHttpResponse (SymfonyComponentHttpFoundationResponse的子類)Laravel中對普通的非JSON響應的定義通過prepareResponse中的邏輯可以看到,無論路由執行結果返回的是什么值最終都會被Laravel轉換為成一個Response對象,而這些對象都是SymfonyComponentHttpFoundationResponse類或者其子類的對象。從這里也就能看出來跟Request一樣Laravel的Response也是依賴Symfony框架的HttpFoundation組件來實現的。
我們來看一下SymfonyComponentHttpFoundationResponse的構造方法:
namespace Symfony/Component/HttpFoundation;class Response public function __construct($content = , $status = 200, $headers = array()) $this- headers = new ResponseHeaderBag($headers); $this- setContent($content); $this- setStatusCode($status); $this- setProtocolVersion( 1.0 //設置響應的Content public function setContent($content) if (null !== $content !is_string($content) !is_numeric($content) !is_callable(array($content, __toString ))) { throw new /UnexpectedValueException(sprintf( The Response content must be a string or object implementing __toString(), %s given. , gettype($content))); $this- content = (string) $content; return $this;}
所以路由處理程序的返回值在創業Response對象時會設置到對象的content屬性里,該屬性的值就是返回給客戶端的響應的響應內容。
設置Response headers生成Response對象后就要執行對象的prepare方法了,該方法定義在Symfony/Component/HttpFoundation/Resposne類中,其主要目的是對Response進行微調使其能夠遵從HTTP/1.1協議(RFC 2616)。
namespace Symfony/Component/HttpFoundation;class Response //在響應被發送給客戶端之前對其進行修訂使其能遵從HTTP/1.1協議 public function prepare(Request $request) $headers = $this- headers; if ($this- isInformational() || $this- isEmpty()) { $this- setContent(null); $headers- remove( Content-Type $headers- remove( Content-Length } else { // Content-type based on the Request if (!$headers- has( Content-Type )) { $format = $request- getRequestFormat(); if (null !== $format $mimeType = $request- getMimeType($format)) { $headers- set( Content-Type , $mimeType); // Fix Content-Type $charset = $this- charset ?: UTF-8 if (!$headers- has( Content-Type )) { $headers- set( Content-Type , text/html; charset= .$charset); } elseif (0 === stripos($headers- get( Content-Type ), text/ ) false === stripos($headers- get( Content-Type ), charset )) { // add the charset $headers- set( Content-Type , $headers- get( Content-Type ). charset= .$charset); // Fix Content-Length if ($headers- has( Transfer-Encoding )) { $headers- remove( Content-Length if ($request- isMethod( HEAD )) { // cf. RFC2616 14.13 $length = $headers- get( Content-Length $this- setContent(null); if ($length) { $headers- set( Content-Length , $length); // Fix protocol if ( HTTP/1.0 != $request- server- get( SERVER_PROTOCOL )) { $this- setProtocolVersion( 1.1 // Check if we need to send extra expire info headers if ( 1.0 == $this- getProtocolVersion() false !== strpos($this- headers- get( Cache-Control ), no-cache )) { $this- headers- set( pragma , no-cache $this- headers- set( expires , -1); $this- ensureIEOverSSLCompatibility($request); return $this;}
prepare里針對各種情況設置了相應的response header 比如Content-Type、Content-Length等等這些我們常見的首部字段。
發送Response創建并設置完Response后它會流經路由和框架中間件的后置操作,在中間件的后置操作里一般都是對Response進行進一步加工,最后程序流回到Http Kernel那里, Http Kernel會把Response發送給客戶端,我們來看一下這部分的代碼。
//入口文件public/index.php$kernel = $app- make(Illuminate/Contracts/Http/Kernel::class);$response = $kernel- handle( $request = Illuminate/Http/Request::capture()$response- send();$kernel- terminate($request, $response);
namespace Symfony/Component/HttpFoundation;class Response public function send() $this- sendHeaders(); $this- sendContent(); if (function_exists( fastcgi_finish_request )) { fastcgi_finish_request(); } elseif ( cli !== PHP_SAPI) { static::closeOutputBuffers(0, true); return $this; //發送headers到客戶端 public function sendHeaders() // headers have already been sent by the developer if (headers_sent()) { return $this; // headers foreach ($this- headers- allPreserveCaseWithoutCookies() as $name = $values) { foreach ($values as $value) { header($name. : .$value, false, $this- statusCode); // status header(sprintf( HTTP/%s %s %s , $this- version, $this- statusCode, $this- statusText), true, $this- statusCode); // cookies foreach ($this- headers- getCookies() as $cookie) { if ($cookie- isRaw()) { setrawcookie($cookie- getName(), $cookie- getValue(), $cookie- getExpiresTime(), $cookie- getPath(), $cookie- getDomain(), $cookie- isSecure(), $cookie- isHttpOnly()); } else { setcookie($cookie- getName(), $cookie- getValue(), $cookie- getExpiresTime(), $cookie- getPath(), $cookie- getDomain(), $cookie- isSecure(), $cookie- isHttpOnly()); return $this; //發送響應內容到客戶端 public function sendContent() echo $this- content; return $this;}
send的邏輯就非常好理解了,把之前設置好的那些headers設置到HTTP響應的首部字段里,Content會echo后被設置到HTTP響應的主體實體中。最后PHP會把完整的HTTP響應發送給客戶端。
send響應后Http Kernel會執行terminate方法調用terminate中間件里的terminate方法,最后執行應用的termiate方法來結束整個應用生命周期(從接收請求開始到返回響應結束)。
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP !
相關推薦:
Laravel核心解讀Request
Laravel核心解讀Facades
以上就是Laravel核心解讀Response的詳細內容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答