当我想分析 Laravel 是如何作到从 Request -> Response 的解析过程的,发现 Lumen 相对简单,因此今天从 Lumen 源代码入手,说一说Request -> Response 的解析过程php
咱们使用 Lumen 项目时,都是经过建立 route
,将请求的方法 method
、路径 uri
和执行 action
关联在一块儿,用于解析 Request
。laravel
如:web
<?php
/* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It is a breeze. Simply tell Lumen the URIs it should respond to | and give it the Closure to call when that URI is requested. | */
// 1️⃣
$router->get('/', function () use ($router) {
return "hello yemeishu ".$router->app->version();
});
// 2️⃣
$router->post('data', 'TempController@index');
复制代码
我先看看 $router
怎么来的:正则表达式
/** * Create a new Lumen application instance. * * @param string|null $basePath * @return void */
public function __construct($basePath = null) {
if (! empty(env('APP_TIMEZONE'))) {
date_default_timezone_set(env('APP_TIMEZONE', 'UTC'));
}
$this->basePath = $basePath;
$this->bootstrapContainer();
$this->registerErrorHandling();
// 这是 Router 引导函数
$this->bootstrapRouter();
}
...
/** * Bootstrap the router instance. * * @return void */
public function bootstrapRouter() {
$this->router = new Router($this);
}
复制代码
有了 $this->router = new Router($this)
,咱们就看 Lumen 是如何装载 routes
的?bootstrap
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
...
/** * Register a set of routes with a set of shared attributes. * * @param array $attributes * @param \Closure $callback * @return void */
public function group(array $attributes, \Closure $callback) {
if (isset($attributes['middleware']) && is_string($attributes['middleware'])) {
$attributes['middleware'] = explode('|', $attributes['middleware']);
}
$this->updateGroupStack($attributes);
call_user_func($callback, $this);
array_pop($this->groupStack);
}
复制代码
先判断传入的 $attributes
是否有中间件「middleware
」,有则解析成数组一并导入到 $this->groupStack[]
中,具体关联的函数以下,代码简单就不作分析了:数组
/** * Update the group stack with the given attributes. * * @param array $attributes * @return void */
protected function updateGroupStack(array $attributes) {
if (! empty($this->groupStack)) {
$attributes = $this->mergeWithLastGroup($attributes);
}
$this->groupStack[] = $attributes;
}
...
/** * Merge the given group attributes with the last added group. * * @param array $new * @return array */
protected function mergeWithLastGroup($new) {
return $this->mergeGroup($new, end($this->groupStack));
}
...
/** * Merge the given group attributes. * * @param array $new * @param array $old * @return array */
public function mergeGroup($new, $old) {
$new['namespace'] = static::formatUsesPrefix($new, $old);
$new['prefix'] = static::formatGroupPrefix($new, $old);
if (isset($new['domain'])) {
unset($old['domain']);
}
if (isset($old['as'])) {
$new['as'] = $old['as'].(isset($new['as']) ? '.'.$new['as'] : '');
}
if (isset($old['suffix']) && ! isset($new['suffix'])) {
$new['suffix'] = $old['suffix'];
}
return array_merge_recursive(Arr::except($old, ['namespace', 'prefix', 'as', 'suffix']), $new);
}
复制代码
注:
$this->groupStack[]
主要数组 keys 包含:namespace
、prefix
、domain
、as
、suffix
,这对下文的分析颇有做用。app
而后执行 call_user_func($callback, $this)
,即回调函数:dom
function ($router) {
require __DIR__.'/../routes/web.php';
}
复制代码
将 web.php
载入到这个函数里,进一步获得函数:ide
function ($router) {
$router->get('/', function () use ($router) {
return "hello yemeishu ".$router->app->version();
});
$router->post('data', 'TempController@index');
}
复制代码
咱们的主角进场了,咱们看看这些 get
、post
函数,基本都是同样的:函数
public function head($uri, $action) {
$this->addRoute('HEAD', $uri, $action);
return $this;
}
public function get($uri, $action) {
$this->addRoute('GET', $uri, $action);
return $this;
}
public function post($uri, $action) {
$this->addRoute('POST', $uri, $action);
return $this;
}
public function put($uri, $action) {
$this->addRoute('PUT', $uri, $action);
return $this;
}
public function patch($uri, $action) {
$this->addRoute('PATCH', $uri, $action);
return $this;
}
public function delete($uri, $action) {
$this->addRoute('DELETE', $uri, $action);
return $this;
}
public function options($uri, $action) {
$this->addRoute('OPTIONS', $uri, $action);
return $this;
}
复制代码
注:这里能够看出 Router 主要是处理这 7个
method
:head
、get
、post
、put
、patch
、delete
、options
执行的都是
$this->addRoute()
函数:
/** * Add a route to the collection. * * @param array|string $method * @param string $uri * @param mixed $action * @return void */
public function addRoute($method, $uri, $action) {
$action = $this->parseAction($action);
$attributes = null;
if ($this->hasGroupStack()) {
$attributes = $this->mergeWithLastGroup([]);
}
if (isset($attributes) && is_array($attributes)) {
if (isset($attributes['prefix'])) {
$uri = trim($attributes['prefix'], '/').'/'.trim($uri, '/');
}
if (isset($attributes['suffix'])) {
$uri = trim($uri, '/').rtrim($attributes['suffix'], '/');
}
$action = $this->mergeGroupAttributes($action, $attributes);
}
$uri = '/'.trim($uri, '/');
if (isset($action['as'])) {
$this->namedRoutes[$action['as']] = $uri;
}
if (is_array($method)) {
foreach ($method as $verb) {
$this->routes[$verb.$uri] = ['method' => $verb, 'uri' => $uri, 'action' => $action];
}
} else {
$this->routes[$method.$uri] = ['method' => $method, 'uri' => $uri, 'action' => $action];
}
}
复制代码
咱们一步步来解析:
$action = $this->parseAction($action);
...
/** * Parse the action into an array format. * * @param mixed $action * @return array */
protected function parseAction($action) {
if (is_string($action)) {
return ['uses' => $action];
} elseif (! is_array($action)) {
return [$action];
}
if (isset($action['middleware']) && is_string($action['middleware'])) {
$action['middleware'] = explode('|', $action['middleware']);
}
return $action;
}
复制代码
将 $action
转为数组,若是传入的参数包含中间件,顺便也转为数组结构。
此方法能够看出,
$action
不只能够是 string 类型,也能够是数组类型,能够传入 key 为:uses
和middleware
如上面例子结果变为:
// 1️⃣
[function () use ($router) {
return "hello yemeishu ".$router->app->version();
}]
// 2️⃣
['uses' => 'TempController@index']
复制代码
继续往下看:
if (isset($attributes) && is_array($attributes)) {
if (isset($attributes['prefix'])) {
$uri = trim($attributes['prefix'], '/').'/'.trim($uri, '/');
}
if (isset($attributes['suffix'])) {
$uri = trim($uri, '/').rtrim($attributes['suffix'], '/');
}
$action = $this->mergeGroupAttributes($action, $attributes);
}
$uri = '/'.trim($uri, '/');
复制代码
这个比较好理解了,只是将「前缀」和「后缀」拼接到 $uri
上。
// 1️⃣
$uri = '/';
// 2️⃣
$uri = '/data';
复制代码
同时,将 $attributes
合并到 $action
。
往下走:
if (isset($action['as'])) {
$this->namedRoutes[$action['as']] = $uri;
}
复制代码
若是 $action
数组还传入 key:as
,则将该 $uri
保存到命名数组中,利用别名与 $uri
关联。
最后处理 $method
了:
if (is_array($method)) {
foreach ($method as $verb) {
$this->routes[$verb.$uri] = ['method' => $verb, 'uri' => $uri, 'action' => $action];
}
} else {
$this->routes[$method.$uri] = ['method' => $method, 'uri' => $uri, 'action' => $action];
}
复制代码
注:这也能够看出
$method
能够传入数组,而且将路由三要素「method
、uri
、action
」存于数组$routes
中,并用$method.$uri
当 key。
到此,咱们基本解读了 Router
这个类的 416行全部代码和功能了。
咱们把全部定义的路由信息都存入 Router
对象中,供 Request
-> Response
使用。
系统的运行,主要就是为了响应各类各样的 Request
,获得 Response
反馈给请求者。
// Lumen 的入口方法
$app->run();
...
// 直接进入代码:Laravel\Lumen\Concerns\RoutesRequests
/** * Run the application and send the response. * * @param SymfonyRequest|null $request * @return void */
public function run($request = null) {
$response = $this->dispatch($request);
if ($response instanceof SymfonyResponse) {
$response->send();
} else {
echo (string) $response;
}
if (count($this->middleware) > 0) {
$this->callTerminableMiddleware($response);
}
}
// $dispatch 执行函数:
/** * Dispatch the incoming request. * * @param SymfonyRequest|null $request * @return Response */
public function dispatch($request = null) {
list($method, $pathInfo) = $this->parseIncomingRequest($request);
try {
return $this->sendThroughPipeline($this->middleware, function () use ($method, $pathInfo) {
if (isset($this->router->getRoutes()[$method.$pathInfo])) {
return $this->handleFoundRoute([true, $this->router->getRoutes()[$method.$pathInfo]['action'], []]);
}
return $this->handleDispatcherResponse(
$this->createDispatcher()->dispatch($method, $pathInfo)
);
});
} catch (Exception $e) {
return $this->prepareResponse($this->sendExceptionToHandler($e));
} catch (Throwable $e) {
return $this->prepareResponse($this->sendExceptionToHandler($e));
}
}
复制代码
庖丁解牛,咱们首要看的是如何利用 parseIncomingRequest()
返回 $method, $pathInfo
的?
list($method, $pathInfo) = $this->parseIncomingRequest($request);
...
/** * Parse the incoming request and return the method and path info. * * @param \Symfony\Component\HttpFoundation\Request|null $request * @return array */
protected function parseIncomingRequest($request) {
if (! $request) {
$request = Request::capture();
}
$this->instance(Request::class, $this->prepareRequest($request));
return [$request->getMethod(), '/'.trim($request->getPathInfo(), '/')];
}
复制代码
这里主要使用 $request->getMethod()
和 $request->getPathInfo()
,这放在对 Request
的分析时再作研究。
咱们接着往下看:
try {
// 第1️⃣步,这是最后执行的,暂且最后分析
return $this->sendThroughPipeline($this->middleware, function () use ($method, $pathInfo) {
if (isset($this->router->getRoutes()[$method.$pathInfo])) {
// 第2️⃣步
return $this->handleFoundRoute([true, $this->router->getRoutes()[$method.$pathInfo]['action'], []]);
}
// 第3️⃣步的执行会调用到「第2️⃣步」方法,因此咱们先研究第3️⃣步
return $this->handleDispatcherResponse(
$this->createDispatcher()->dispatch($method, $pathInfo)
);
});
} catch (Exception $e) {
return $this->prepareResponse($this->sendExceptionToHandler($e));
} catch (Throwable $e) {
return $this->prepareResponse($this->sendExceptionToHandler($e));
}
复制代码
「第3️⃣步」的 $this->createDispatcher()->dispatch($method, $pathInfo)
主要是返回数组结构以下:
<?php
namespace FastRoute;
interface Dispatcher {
const NOT_FOUND = 0;
const FOUND = 1;
const METHOD_NOT_ALLOWED = 2;
/** * Dispatches against the provided HTTP method verb and URI. * * Returns array with one of the following formats: * * [self::NOT_FOUND] * [self::METHOD_NOT_ALLOWED, ['GET', 'OTHER_ALLOWED_METHODS']] * [self::FOUND, $handler, ['varName' => 'value', ...]] * * @param string $httpMethod * @param string $uri * * @return array */
public function dispatch($httpMethod, $uri);
}
复制代码
咱们接着看是如何实现 Dispatcher
的?
/** * Create a FastRoute dispatcher instance for the application. * * @return Dispatcher */
protected function createDispatcher() {
return $this->dispatcher ?: \FastRoute\simpleDispatcher(function ($r) {
foreach ($this->router->getRoutes() as $route) {
$r->addRoute($route['method'], $route['uri'], $route['action']);
}
});
}
复制代码
这里的 \FastRoute\simpleDispatcher()
是一个全局函数:
/** * @param callable $routeDefinitionCallback * @param array $options * * @return Dispatcher */
function simpleDispatcher(callable $routeDefinitionCallback, array $options = []) {
$options += [
'routeParser' => 'FastRoute\\RouteParser\\Std',
'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased',
'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased',
'routeCollector' => 'FastRoute\\RouteCollector',
];
/** @var RouteCollector $routeCollector */
$routeCollector = new $options['routeCollector'](
new $options['routeParser'], new $options['dataGenerator']
);
$routeDefinitionCallback($routeCollector);
return new $options['dispatcher']($routeCollector->getData());
}
复制代码
这个方法主要利用 new FastRoute\\RouteParser\\Std()
和 new FastRoute\\DataGenerator\\GroupCountBased()
来建立 routeCollector
对象,用于存储全部 route
:
function ($routeCollector) {
foreach ($this->router->getRoutes() as $route) {
$routeCollector->addRoute($route['method'], $route['uri'], $route['action']);
}
}
复制代码
咱们继续看 addRoute()
方法:
/** * Adds a route to the collection. * * The syntax used in the $route string depends on the used route parser. * * @param string|string[] $httpMethod * @param string $route * @param mixed $handler */
public function addRoute($httpMethod, $route, $handler) {
$route = $this->currentGroupPrefix . $route;
$routeDatas = $this->routeParser->parse($route);
foreach ((array) $httpMethod as $method) {
foreach ($routeDatas as $routeData) {
$this->dataGenerator->addRoute($method, $routeData, $handler);
}
}
}
复制代码
这里有两个方法咱们能够往下研究:$this->routeParser->parse($route)
解析 $route
这个暂且不表,和 $this->dataGenerator->addRoute($method, $routeData, $handler)
收集路由信息:
public function addRoute($httpMethod, $routeData, $handler) {
if ($this->isStaticRoute($routeData)) {
$this->addStaticRoute($httpMethod, $routeData, $handler);
} else {
$this->addVariableRoute($httpMethod, $routeData, $handler);
}
}
复制代码
这里主要分红两种状况,一种是单一路由数据,保存在数组 $staticRoutes
中,另外一种是正则表达式路由数据,存于 $methodToRegexToRoutesMap
中。咱们此时更关心之后怎么使用这两个数组数据。
最后就是建立分发器 FastRoute\\Dispatcher\\GroupCountBased
:
// 其中 `$routeCollector->getData()` 后续继续研究
return new $options['dispatcher']($routeCollector->getData());
...
class GroupCountBased extends RegexBasedAbstract {
public function __construct($data) {
list($this->staticRouteMap, $this->variableRouteData) = $data;
}
protected function dispatchVariableRoute($routeData, $uri) {
foreach ($routeData as $data) {
if (!preg_match($data['regex'], $uri, $matches)) {
continue;
}
list($handler, $varNames) = $data['routeMap'][count($matches)];
$vars = [];
$i = 0;
foreach ($varNames as $varName) {
$vars[$varName] = $matches[++$i];
}
return [self::FOUND, $handler, $vars];
}
return [self::NOT_FOUND];
}
}
复制代码
建立了 dispatcher
分配器以后,咱们就能够考虑怎么使用了。
$this->createDispatcher()->dispatch($method, $pathInfo)
复制代码
分派方法,无非从上面的两个数组中去寻找对应 method 和 uri,以得到 handler
。
<?php
namespace FastRoute\Dispatcher;
use FastRoute\Dispatcher;
abstract class RegexBasedAbstract implements Dispatcher {
/** @var mixed[][] */
protected $staticRouteMap = [];
/** @var mixed[] */
protected $variableRouteData = [];
/** * @return mixed[] */
abstract protected function dispatchVariableRoute($routeData, $uri);
public function dispatch($httpMethod, $uri) {
if (isset($this->staticRouteMap[$httpMethod][$uri])) {
$handler = $this->staticRouteMap[$httpMethod][$uri];
return [self::FOUND, $handler, []];
}
$varRouteData = $this->variableRouteData;
if (isset($varRouteData[$httpMethod])) {
$result = $this->dispatchVariableRoute($varRouteData[$httpMethod], $uri);
if ($result[0] === self::FOUND) {
return $result;
}
}
// For HEAD requests, attempt fallback to GET
if ($httpMethod === 'HEAD') {
if (isset($this->staticRouteMap['GET'][$uri])) {
$handler = $this->staticRouteMap['GET'][$uri];
return [self::FOUND, $handler, []];
}
if (isset($varRouteData['GET'])) {
$result = $this->dispatchVariableRoute($varRouteData['GET'], $uri);
if ($result[0] === self::FOUND) {
return $result;
}
}
}
// If nothing else matches, try fallback routes
if (isset($this->staticRouteMap['*'][$uri])) {
$handler = $this->staticRouteMap['*'][$uri];
return [self::FOUND, $handler, []];
}
if (isset($varRouteData['*'])) {
$result = $this->dispatchVariableRoute($varRouteData['*'], $uri);
if ($result[0] === self::FOUND) {
return $result;
}
}
// Find allowed methods for this URI by matching against all other HTTP methods as well
$allowedMethods = [];
foreach ($this->staticRouteMap as $method => $uriMap) {
if ($method !== $httpMethod && isset($uriMap[$uri])) {
$allowedMethods[] = $method;
}
}
foreach ($varRouteData as $method => $routeData) {
if ($method === $httpMethod) {
continue;
}
$result = $this->dispatchVariableRoute($routeData, $uri);
if ($result[0] === self::FOUND) {
$allowedMethods[] = $method;
}
}
// If there are no allowed methods the route simply does not exist
if ($allowedMethods) {
return [self::METHOD_NOT_ALLOWED, $allowedMethods];
}
return [self::NOT_FOUND];
}
}
...
protected function dispatchVariableRoute($routeData, $uri) {
foreach ($routeData as $data) {
if (!preg_match($data['regex'], $uri, $matches)) {
continue;
}
list($handler, $varNames) = $data['routeMap'][count($matches)];
$vars = [];
$i = 0;
foreach ($varNames as $varName) {
$vars[$varName] = $matches[++$i];
}
return [self::FOUND, $handler, $vars];
}
return [self::NOT_FOUND];
}
复制代码
以上解析过程比较简单,就不用解释了。
获得 handler
后,咱们就能够处理 $request
,获得 $response
结果。
/** * Handle the response from the FastRoute dispatcher. * * @param array $routeInfo * @return mixed */
protected function handleDispatcherResponse($routeInfo) {
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
throw new NotFoundHttpException;
case Dispatcher::METHOD_NOT_ALLOWED:
throw new MethodNotAllowedHttpException($routeInfo[1]);
case Dispatcher::FOUND:
return $this->handleFoundRoute($routeInfo);
}
}
复制代码
咱们不分析前两个分支,咱们主要考虑 Dispatcher::FOUND
这种状况,即:$this->handleFoundRoute($routeInfo)
/** * Handle a route found by the dispatcher. * * @param array $routeInfo * @return mixed */
protected function handleFoundRoute($routeInfo) {
$this->currentRoute = $routeInfo;
$this['request']->setRouteResolver(function () {
return $this->currentRoute;
});
$action = $routeInfo[1];
// Pipe through route middleware...
if (isset($action['middleware'])) {
$middleware = $this->gatherMiddlewareClassNames($action['middleware']);
return $this->prepareResponse($this->sendThroughPipeline($middleware, function () {
return $this->callActionOnArrayBasedRoute($this['request']->route());
}));
}
return $this->prepareResponse(
$this->callActionOnArrayBasedRoute($routeInfo)
);
}
复制代码
咱们暂时也不去考虑是否存在「中间件」的问题,那么把目光就锁定在最后一条语句上了。
/** * Call the Closure on the array based route. * * @param array $routeInfo * @return mixed */
protected function callActionOnArrayBasedRoute($routeInfo) {
$action = $routeInfo[1];
if (isset($action['uses'])) {
return $this->prepareResponse($this->callControllerAction($routeInfo));
}
foreach ($action as $value) {
if ($value instanceof Closure) {
$closure = $value->bindTo(new RoutingClosure);
break;
}
}
try {
return $this->prepareResponse($this->call($closure, $routeInfo[2]));
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
复制代码
到此,咱们终于开始进入「Controller」级别的分析了。
先看第一种状况:$this->callControllerAction($routeInfo)
如上面的第2️⃣种状况:
// 2️⃣
['uses' => 'TempController@index']
复制代码
/** * Call a controller based route. * * @param array $routeInfo * @return mixed */
protected function callControllerAction($routeInfo) {
$uses = $routeInfo[1]['uses'];
if (is_string($uses) && ! Str::contains($uses, '@')) {
$uses .= '@__invoke';
}
list($controller, $method) = explode('@', $uses);
if (! method_exists($instance = $this->make($controller), $method)) {
throw new NotFoundHttpException;
}
if ($instance instanceof LumenController) {
return $this->callLumenController($instance, $method, $routeInfo);
} else {
return $this->callControllerCallable(
[$instance, $method], $routeInfo[2]
);
}
}
复制代码
这个对于咱们每天写 Lumen or Laravel 代码的咱们来讲,挺好理解的,经过利用「@」分解 controller
和 method
;再利用 $this->make($controller)
获得 Controller
对象,若是是 LumenController
类型,则须要去判断是否有中间件一个环节。最后都是调用 $this->callControllerCallable([$instance, $method], $routeInfo[2])
:
protected function callControllerCallable(callable $callable, array $parameters = []) {
try {
return $this->prepareResponse(
$this->call($callable, $parameters)
);
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
...
/** * Call the given Closure / class@method and inject its dependencies. * * @param callable|string $callback * @param array $parameters * @param string|null $defaultMethod * @return mixed */
public function call($callback, array $parameters = [], $defaultMethod = null) {
return BoundMethod::call($this, $callback, $parameters, $defaultMethod);
}
复制代码
来反射解析类和方法,调用方法,返回结果。具体能够详细研究 illuminate\\container\\BoundMethod
类。
封装成 Response
结果:
return $this->prepareResponse(
$this->call($callable, $parameters)
);
/** * Prepare the response for sending. * * @param mixed $response * @return Response */
public function prepareResponse($response) {
if ($response instanceof Responsable) {
$response = $response->toResponse(Request::capture());
}
if ($response instanceof PsrResponseInterface) {
$response = (new HttpFoundationFactory)->createResponse($response);
} elseif (! $response instanceof SymfonyResponse) {
$response = new Response($response);
} elseif ($response instanceof BinaryFileResponse) {
$response = $response->prepare(Request::capture());
}
return $response;
}
复制代码
起始亦是终,最后把 Response
输出,回到最开始的 run
方法
public function run($request = null) {
$response = $this->dispatch($request);
if ($response instanceof SymfonyResponse) {
$response->send();
} else {
echo (string) $response;
}
if (count($this->middleware) > 0) {
$this->callTerminableMiddleware($response);
}
}
复制代码
到此,咱们终于分析了走了一遍较为完整的从 Request
到最后的 Response
的流程。此文结合 Lumen 文档 lumen.laravel.com/docs/5.6/ro… 来看,效果会更好的。
这过程咱们也发现了几个彩蛋:
彩蛋1️⃣ $router->addRoute($method, $uri, $action)
的 method
能够传入数组,如 ['GET', 'POST']
彩蛋2️⃣
if (! method_exists($instance = $this->make($controller), $method)) {
throw new NotFoundHttpException;
}
if ($instance instanceof LumenController) {
return $this->callLumenController($instance, $method, $routeInfo);
} else {
return $this->callControllerCallable(
[$instance, $method], $routeInfo[2]
);
}
复制代码
能够看出,处理咱们 route
的类能够不用继承「Controller
」,只要依赖注入,能利用 $this->make
解析到的「类」都可。
最后,咱们还有不少须要深刻研究的内容,如:中间件 middleware
、Pipeline
原理、Request
解析、带有正则表达式的 $uri
是怎么解析的,等等。
未完待续