作为程序员一定要保持良好的睡眠,才能好编程

第十一课laravel路由运行规则

发布时间:2018-10-09


lumne路由执行顺序:


1、入口文件index.php run方法

2、run()方法 Concerns\RoutesRequests(vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php)

<?php
trait RoutesRequests
{
    ......
    public function run($request = null)
    {
        $response = $this->dispatch($request); // 处理请求 (中间件 等)
        if ($response instanceof SymfonyResponse) {
            $response->send(); // 返回 http 请求结果
        } else {
            echo (string) $response;
        }
        // 处理 middleware 中的 terminate() -->终止中间件 (有时候中间件可能需要在 HTTP 响应发送到浏览器之后做一些工作)
        if (count($this->middleware) > 0) {
            $this->callTerminableMiddleware($response);
        }
    }

 

 3、dispatch 路由方法

<?php
trait RoutesRequests
{
    ......
    /**
     * Dispatch the incoming request.
     *
     * @param  SymfonyRequest|null  $request
     * @return Response
     */
    public function dispatch($request = null)
    {
        // 初始化 $request
        list($method, $pathInfo) = $this->parseIncomingRequest($request);
        try {
            // pipeline 处理 全局 中间件 
            return $this->sendThroughPipeline($this->middleware, function () use ($method, $pathInfo) { 
                if (isset($this->router->getRoutes()[$method.$pathInfo])) {
                   // handleFoundRoute() 处理  route中间件 
                    return $this->handleFoundRoute([true, $this->router->getRoutes()[$method.$pathInfo]['action'], []]);
                }
                // 处理 没有 路由到的 请求404
                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));
        }
    }

 

   

4、$this->sendThroughPipeline(array $middleware, Closure $then) Concerns\RoutesRequests(vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php)


<?php
trait RoutesRequests
{
    ......
    /**
     * Send the request through the pipeline with the given callback.
     *
     * @param  array  $middleware
     * @param  \Closure  $then
     * @return mixed
     */
    protected function sendThroughPipeline(array $middleware, Closure $then)
    {
        if (count($middleware) > 0 && ! $this->shouldSkipMiddleware()) {
            // pipeline 实现中间件
            return (new Pipeline($this))
                ->send($this->make('request'))
                ->through($middleware)
                ->then($then);
        }
        return $then();
    }