>  기사  >  PHP 프레임워크  >  라라벨 라우팅이 무엇인가요?

라라벨 라우팅이 무엇인가요?

青灯夜游
青灯夜游원래의
2021-09-02 11:57:262644검색

laravel에서 라우팅은 외부 세계가 Laravel 애플리케이션에 액세스하는 방법이거나, 라우팅은 Laravel 애플리케이션이 외부 세계에 서비스를 제공하는 특정 방식을 정의합니다. 라우팅은 미리 계획된 계획에 따라 처리하기 위해 지정된 컨트롤러 및 방법에 사용자의 요청을 제출합니다.

라라벨 라우팅이 무엇인가요?

이 튜토리얼의 운영 환경: Windows 7 시스템, Laravel 6 버전, DELL G3 컴퓨터.

라우팅은 외부 세계가 Laravel 애플리케이션에 액세스하는 방법입니다. 또는 라우팅은 Laravel 애플리케이션이 외부 세계에 서비스를 제공하는 특정 방식을 정의합니다. 지정된 URI, HTTP 요청 방법 및 라우팅 매개변수(선택 사항)를 통해서만 라우팅 정의에 올바르게 액세스해야 합니다.

URI에 해당하는 핸들러가 단순 클로저이거나 컨트롤러 메서드에 해당 경로가 없으면 외부 세계에서는 해당 경로에 접근할 수 없습니다.

오늘은 Laravel이 어떻게 라우팅을 설계하고 구현하는지 살펴보겠습니다.

우리는 일반적으로 라우팅 파일에 다음과 같이 경로를 정의합니다.

Route::get('/user', 'UsersController@index');

위의 라우팅을 통해 클라이언트가 HTTP GET을 통해 URI "/user"를 요청하면 Laravel이 요청을 마무리한다는 것을 알 수 있습니다. 처리를 위해 UsersController 클래스의 인덱스 메서드를 사용한 다음 인덱스 메서드에서 클라이언트에 응답을 반환합니다.

위의 경로를 등록할 때 사용한 Route 클래스는 Laravel에서 Facade라고 하며 서비스 컨테이너에 바인딩된 서비스 라우터에 액세스하는 간단한 방법을 제공합니다. 앞으로 Facade의 설계 개념과 구현에 대해 논의할 예정입니다. 별도의 블로그 게시물에서, 여기서는 호출되는 Route 파사드의 정적 메소드가 서비스 컨테이너의 라우터 서비스 메소드에 해당한다는 것만 알면 됩니다. 따라서 위의 경로를 다음과 같이 등록할 수도 있습니다:

app()->make('router')->get('user', 'UsersController@index');

router 이 서비스는 애플리케이션을 인스턴스화할 때 생성자에 RoutingServiceProvider를 등록하여 서비스 컨테이너에 바인딩됩니다. 애플리케이션:

//bootstrap/app.php
$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

//Application: 构造方法
public function __construct($basePath = null)
{
    if ($basePath) {
        $this->setBasePath($basePath);
    }

    $this->registerBaseBindings();

    $this->registerBaseServiceProviders();

    $this->registerCoreContainerAliases();
}

//Application: 注册基础的服务提供器
protected function registerBaseServiceProviders()
{
    $this->register(new EventServiceProvider($this));

    $this->register(new LogServiceProvider($this));

    $this->register(new RoutingServiceProvider($this));
}

//\Illuminate\Routing\RoutingServiceProvider: 绑定router到服务容器
protected function registerRouter()
{
    $this->app->singleton('router', function ($app) {
        return new Router($app['events'], $app);
    });
}

위 코드를 통해 Route에 의해 호출된 정적 메서드는 모두 IlluminateRoutingRouter code>메서드에 해당한다는 것을 알 수 있습니다. 클래스 중 Router 클래스에는 라우팅 등록, 주소 지정 및 스케줄링과 관련된 메소드가 포함되어 있습니다. <code>IlluminateRoutingRouter类里的方法,Router这个类里包含了与路由的注册、寻址、调度相关的方法。

下面我们从路由的注册、加载、寻址这几个阶段来看一下laravel里是如何实现这些的。

路由加载

注册路由前需要先加载路由文件,路由文件的加载是在AppProvidersRouteServiceProvider这个服务器提供者的boot方法里加载的:

class RouteServiceProvider extends ServiceProvider
{
    public function boot()
    {
        parent::boot();
    }

    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();
    }

    protected function mapWebRoutes()
    {
        Route::middleware(&#39;web&#39;)
             ->namespace($this->namespace)
             ->group(base_path(&#39;routes/web.php&#39;));
    }

    protected function mapApiRoutes()
    {
        Route::prefix(&#39;api&#39;)
             ->middleware(&#39;api&#39;)
             ->namespace($this->namespace)
             ->group(base_path(&#39;routes/api.php&#39;));
    }
}
namespace Illuminate\Foundation\Support\Providers;

class RouteServiceProvider extends ServiceProvider
{

    public function boot()
    {
        $this->setRootControllerNamespace();

        if ($this->app->routesAreCached()) {
            $this->loadCachedRoutes();
        } else {
            $this->loadRoutes();

            $this->app->booted(function () {
                $this->app[&#39;router&#39;]->getRoutes()->refreshNameLookups();
                $this->app[&#39;router&#39;]->getRoutes()->refreshActionLookups();
            });
        }
    }

    protected function loadCachedRoutes()
    {
        $this->app->booted(function () {
            require $this->app->getCachedRoutesPath();
        });
    }

    protected function loadRoutes()
    {
        if (method_exists($this, &#39;map&#39;)) {
            $this->app->call([$this, &#39;map&#39;]);
        }
    }
}

class Application extends Container implements ApplicationContract, HttpKernelInterface
{
    public function routesAreCached()
    {
        return $this[&#39;files&#39;]->exists($this->getCachedRoutesPath());
    }

    public function getCachedRoutesPath()
    {
        return $this->bootstrapPath().&#39;/cache/routes.php&#39;;
    }
}

laravel 首先去寻找路由的缓存文件,没有缓存文件再去进行加载路由。缓存文件一般在 bootstrap/cache/routes.php 文件中。
方法loadRoutes会调用map方法来加载路由文件里的路由,map这个函数在AppProvidersRouteServiceProvider类中,这个类继承自IlluminateFoundationSupportProvidersRouteServiceProvider。通过map方法我们能看到laravel将路由分为两个大组:api、web。这两个部分的路由分别写在两个文件中:routes/web.php、routes/api.php。

Laravel5.5里是把路由分别放在了几个文件里,之前的版本是在app/Http/routes.php文件里。放在多个文件里能更方便地管理API路由和与WEB路由

路由注册

我们通常都是用Route这个Facade调用静态方法get, post, head, options, put, patch, delete......等来注册路由,上面我们也说了这些静态方法其实是调用了Router类里的方法:

public function get($uri, $action = null)
{
    return $this->addRoute([&#39;GET&#39;, &#39;HEAD&#39;], $uri, $action);
}

public function post($uri, $action = null)
{
    return $this->addRoute(&#39;POST&#39;, $uri, $action);
}
....

可以看到路由的注册统一都是由router类的addRoute方法来处理的:

//注册路由到RouteCollection
protected function addRoute($methods, $uri, $action)
{
    return $this->routes->add($this->createRoute($methods, $uri, $action));
}

//创建路由
protected function createRoute($methods, $uri, $action)
{
    if ($this->actionReferencesController($action)) {
        //controller@action类型的路由在这里要进行转换
        $action = $this->convertToControllerAction($action);
    }

    $route = $this->newRoute(
        $methods, $this->prefix($uri), $action
    );

    if ($this->hasGroupStack()) {
        $this->mergeGroupAttributesIntoRoute($route);
    }

    $this->addWhereClausesToRoute($route);

    return $route;
}

protected function convertToControllerAction($action)
{
    if (is_string($action)) {
        $action = [&#39;uses&#39; => $action];
    }

    if (! empty($this->groupStack)) {        
        $action[&#39;uses&#39;] = $this->prependGroupNamespace($action[&#39;uses&#39;]);
    }
    
    $action[&#39;controller&#39;] = $action[&#39;uses&#39;];

    return $action;
}

注册路由时传递给addRoute的第三个参数action可以闭包、字符串或者数组,数组就是类似['uses' => 'Controller@action', 'middleware' => '...']这种形式的。如果action是Controller@action类型的路由将被转换为action数组, convertToControllerAction执行完后action的内容为:

[
    &#39;uses&#39; => &#39;App\Http\Controllers\SomeController@someAction&#39;,
    &#39;controller&#39; => &#39;App\Http\Controllers\SomeController@someAction&#39;
]

可以看到把命名空间补充到了控制器的名称前组成了完整的控制器类名,action数组构建完成接下里就是创建路由了,创建路由即用指定的HTTP请求方法、URI字符串和action数组来创建IlluminateRoutingRoute

라우팅 등록, 로딩, 어드레싱 단계부터 Laravel에서 어떻게 구현되는지 살펴보겠습니다.

경로 로딩

경로를 등록하기 전에 라우팅 파일을 로드해야 합니다. 라우팅 파일은 AppProvidersRouteServiceProvider이 서버 공급자의 부팅 방법에 로드됨:<p><pre class="brush:js;toolbar:false;">protected function newRoute($methods, $uri, $action) { return (new Route($methods, $uri, $action)) -&gt;setRouter($this) -&gt;setContainer($this-&gt;container); }</pre><pre class="brush:js;toolbar:false;">protected function addRoute($methods, $uri, $action) { return $this-&gt;routes-&gt;add($this-&gt;createRoute($methods, $uri, $action)); }</pre></p>laravel은 먼저 경로의 캐시 파일을 찾은 다음 캐시 파일이 없으면 경로를 로드합니다. 캐시 파일은 일반적으로 bootstrap/cache/routes.php 파일에 있습니다. <p>loadRoutes 메소드는 라우팅 파일에 경로를 로드하기 위해 map 메소드를 호출합니다. 지도 함수는 <code>IlluminateFoundationSupportProvidersRouteServiceProvider에서 상속되는 AppProvidersRouteServiceProvider 클래스에 있습니다. map 메소드를 통해 우리는 laravel이 라우팅을 api와 web이라는 두 개의 큰 그룹으로 나누는 것을 볼 수 있습니다. 이 두 부분에 대한 경로는 각각 Routes/web.php 및 Routes/api.php라는 두 개의 파일로 작성됩니다.

Laravel 5.5에서는 경로가 여러 파일에 배치됩니다. 이전 버전은 app/Http/routes.php 파일에 있었습니다. 여러 파일에 넣어두면 API 라우팅 및 WEB 라우팅 관리가 더 쉬워집니다

경로 등록 Strong>

우리는 일반적으로 Route Facade를 사용하여 get, post, head, options, put, patch, delete 등의 정적 메서드를 호출하여 경로를 등록합니다. 또한 위에서 이러한 정적 메서드는 실제로는 라우터 클래스는 다음과 같습니다.

class RouteCollection implements Countable, IteratorAggregate
{
    public function add(Route $route)
    {
        $this->addToCollections($route);

        $this->addLookups($route);

        return $route;
    }
    
    protected function addToCollections($route)
    {
        $domainAndUri = $route->getDomain().$route->uri();

        foreach ($route->methods() as $method) {
            $this->routes[$method][$domainAndUri] = $route;
        }

        $this->allRoutes[$method.$domainAndUri] = $route;
    }
    
    protected function addLookups($route)
    {
        $action = $route->getAction();

        if (isset($action[&#39;as&#39;])) {
            //如果时命名路由,将route对象映射到以路由名为key的数组值中方便查找
            $this->nameList[$action[&#39;as&#39;]] = $route;
        }

        if (isset($action[&#39;controller&#39;])) {
            $this->addToActionList($action, $route);
        }
    }

}

경로 등록이 라우터 클래스의 addRoute 메서드에 의해 처리되는 것을 볼 수 있습니다.

[
    &#39;GET&#39; => [
        $routeUri1 => $routeObj1
        ...
    ]
    ...
]
🎜경로 등록 시 addRoute에 전달되는 세 번째 매개변수 작업은 클로저 또는 문자열 또는 문자열일 수 있습니다. array, array는 ['uses' => 'Controller@action', 'middleware' => '...']와 유사합니다. 액션이 Controller@action 유형의 경로인 경우 액션 배열로 변환됩니다. ConvertToControllerAction이 실행된 후 액션의 내용은 다음과 같습니다. 🎜
[
    &#39;GET&#39; . $routeUri1 => $routeObj1
    &#39;GET&#39; . $routeUri2 => $routeObj2
    ...
]
🎜네임스페이스가 컨트롤러 이름 앞에 추가됩니다. 다음 단계는 경로를 만드는 것입니다. 지정된 HTTP 요청 메서드, URI 문자열 및 작업 배열을 사용하여 IlluminateRoutingRoute 클래스: 🎜
[
    $routeName1 => $routeObj1
    ...
]
🎜 경로 생성이 완료된 후 RouteCollection에 경로를 추가합니다. 🎜
[
    &#39;App\Http\Controllers\ControllerOne@ActionOne&#39; => $routeObj1
]
🎜라우터의 $routes 속성은 RouteCollection에 경로를 추가할 때입니다. 🎜
//Illuminate\Foundation\Http\Kernel
class Kernel implements KernelContract
{
    protected function sendRequestThroughRouter($request)
    {
        $this->app->instance(&#39;request&#39;, $request);

        Facade::clearResolvedInstance(&#39;request&#39;);

        $this->bootstrap();

        return (new Pipeline($this->app))
                    ->send($request)
                    ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
                    ->then($this->dispatchToRouter());
    }
    
    protected function dispatchToRouter()
    {
        return function ($request) {
            $this->app->instance(&#39;request&#39;, $request);

            return $this->router->dispatch($request);
        };
    }
    
}
🎜RouteCollection 4개의 🎜🎜routes 속성은 HTTP 요청 메소드와 라우팅 객체 간의 매핑을 저장합니다. 🎜
$destination = function ($request) {
    $this->app->instance(&#39;request&#39;, $request);
    return $this->router->dispatch($request);
};
🎜allRoutes 속성에 저장된 콘텐츠는 다음과 같습니다. 경로 속성의 두 자리 배열을 한 자리 배열로 프로그래밍한 후의 내용: 🎜
class Router implements RegistrarContract, BindingRegistrar
{    
    public function dispatch(Request $request)
    {
        $this->currentRequest = $request;

        return $this->dispatchToRoute($request);
    }
    
    public function dispatchToRoute(Request $request)
    {
        return $this->runRoute($request, $this->findRoute($request));
    }
    
    protected function findRoute($request)
    {
        $this->current = $route = $this->routes->match($request);

        $this->container->instance(Route::class, $route);

        return $route;
    }
    
}
🎜nameList는 라우팅 이름과 라우팅 개체 간의 매핑 테이블입니다. 🎜
class RouteCollection implements Countable, IteratorAggregate
{
    public function match(Request $request)
    {
        $routes = $this->get($request->getMethod());

        $route = $this->matchAgainstRoutes($routes, $request);

        if (! is_null($route)) {
            //找到匹配的路由后,将URI里的路径参数绑定赋值给路由(如果有的话)
            return $route->bind($request);
        }

        $others = $this->checkForAlternateVerbs($request);

        if (count($others) > 0) {
            return $this->getRouteForMethods($request, $others);
        }

        throw new NotFoundHttpException;
    }

    protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true)
    {
        return Arr::first($routes, function ($value) use ($request, $includingMethod) {
            return $value->matches($request, $includingMethod);
        });
    }
}

class Route
{
    public function matches(Request $request, $includingMethod = true)
    {
        $this->compileRoute();

        foreach ($this->getValidators() as $validator) {
            if (! $includingMethod && $validator instanceof MethodValidator) {
                continue;
            }

            if (! $validator->matches($this, $request)) {
                return false;
            }
        }

        return true;
    }
}
🎜actionList는 라우팅 컨트롤러 메서드 문자열과 라우팅 개체 간의 매핑 테이블입니다. 🎜
class UriValidator implements ValidatorInterface
{
    public function matches(Route $route, Request $request)
    {
        $path = $request->path() == &#39;/&#39; ? &#39;/&#39; : &#39;/&#39;.$request->path();

        return preg_match($route->getCompiled()->getRegex(), rawurldecode($path));
    }
}
🎜 이렇게 경로가 등록됩니다. 🎜

路由寻址

中间件的文章里我们说过HTTP请求在经过Pipeline通道上的中间件的前置操作后到达目的地:

//Illuminate\Foundation\Http\Kernel
class Kernel implements KernelContract
{
    protected function sendRequestThroughRouter($request)
    {
        $this->app->instance(&#39;request&#39;, $request);

        Facade::clearResolvedInstance(&#39;request&#39;);

        $this->bootstrap();

        return (new Pipeline($this->app))
                    ->send($request)
                    ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
                    ->then($this->dispatchToRouter());
    }
    
    protected function dispatchToRouter()
    {
        return function ($request) {
            $this->app->instance(&#39;request&#39;, $request);

            return $this->router->dispatch($request);
        };
    }
    
}

上面代码可以看到Pipeline的destination就是dispatchToRouter函数返回的闭包:

$destination = function ($request) {
    $this->app->instance(&#39;request&#39;, $request);
    return $this->router->dispatch($request);
};

在闭包里调用了router的dispatch方法,路由寻址就发生在dispatch的第一个阶段findRoute里:

class Router implements RegistrarContract, BindingRegistrar
{    
    public function dispatch(Request $request)
    {
        $this->currentRequest = $request;

        return $this->dispatchToRoute($request);
    }
    
    public function dispatchToRoute(Request $request)
    {
        return $this->runRoute($request, $this->findRoute($request));
    }
    
    protected function findRoute($request)
    {
        $this->current = $route = $this->routes->match($request);

        $this->container->instance(Route::class, $route);

        return $route;
    }
    
}

寻找路由的任务由 RouteCollection 负责,这个函数负责匹配路由,并且把 request 的 url 参数绑定到路由中:

class RouteCollection implements Countable, IteratorAggregate
{
    public function match(Request $request)
    {
        $routes = $this->get($request->getMethod());

        $route = $this->matchAgainstRoutes($routes, $request);

        if (! is_null($route)) {
            //找到匹配的路由后,将URI里的路径参数绑定赋值给路由(如果有的话)
            return $route->bind($request);
        }

        $others = $this->checkForAlternateVerbs($request);

        if (count($others) > 0) {
            return $this->getRouteForMethods($request, $others);
        }

        throw new NotFoundHttpException;
    }

    protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true)
    {
        return Arr::first($routes, function ($value) use ($request, $includingMethod) {
            return $value->matches($request, $includingMethod);
        });
    }
}

class Route
{
    public function matches(Request $request, $includingMethod = true)
    {
        $this->compileRoute();

        foreach ($this->getValidators() as $validator) {
            if (! $includingMethod && $validator instanceof MethodValidator) {
                continue;
            }

            if (! $validator->matches($this, $request)) {
                return false;
            }
        }

        return true;
    }
}

$routes = $this->get($request->getMethod());会先加载注册路由阶段在RouteCollection里生成的routes属性里的值,routes中存放了HTTP请求方法与路由对象的映射。

然后依次调用这堆路由里路由对象的matches方法, matches方法, matches方法里会对HTTP请求对象进行一些验证,验证对应的Validator是:UriValidator、MethodValidator、SchemeValidator、HostValidator。
在验证之前在$this->compileRoute()里会将路由的规则转换成正则表达式。

UriValidator主要是看请求对象的URI是否与路由的正则规则匹配能匹配上:

class UriValidator implements ValidatorInterface
{
    public function matches(Route $route, Request $request)
    {
        $path = $request->path() == &#39;/&#39; ? &#39;/&#39; : &#39;/&#39;.$request->path();

        return preg_match($route->getCompiled()->getRegex(), rawurldecode($path));
    }
}

MethodValidator验证请求方法, SchemeValidator验证协议是否正确(http|https), HostValidator验证域名, 如果路由中不设置host属性,那么这个验证不会进行。

一旦某个路由通过了全部的认证就将会被返回,接下来就要将请求对象URI里的路径参数绑定赋值给路由参数:

路由参数绑定

class Route
{
    public function bind(Request $request)
    {
        $this->compileRoute();

        $this->parameters = (new RouteParameterBinder($this))
                        ->parameters($request);

        return $this;
    }
}

class RouteParameterBinder
{
    public function parameters($request)
    {
        $parameters = $this->bindPathParameters($request);

        if (! is_null($this->route->compiled->getHostRegex())) {
            $parameters = $this->bindHostParameters(
                $request, $parameters
            );
        }

        return $this->replaceDefaults($parameters);
    }
    
    protected function bindPathParameters($request)
    {
            preg_match($this->route->compiled->getRegex(), &#39;/&#39;.$request->decodedPath(), $matches);

            return $this->matchToKeys(array_slice($matches, 1));
    }
    
    protected function matchToKeys(array $matches)
    {
        if (empty($parameterNames = $this->route->parameterNames())) {
            return [];
        }

        $parameters = array_intersect_key($matches, array_flip($parameterNames));

        return array_filter($parameters, function ($value) {
            return is_string($value) && strlen($value) > 0;
        });
    }
}

赋值路由参数完成后路由寻址的过程就结束了,结下来就该运行通过匹配路由中对应的控制器方法返回响应对象了。

class Router implements RegistrarContract, BindingRegistrar
{    
    public function dispatch(Request $request)
    {
        $this->currentRequest = $request;

        return $this->dispatchToRoute($request);
    }
    
    public function dispatchToRoute(Request $request)
    {
        return $this->runRoute($request, $this->findRoute($request));
    }
    
    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(&#39;middleware.disable&#39;) &&
                            $this->container->make(&#39;middleware.disable&#39;) === 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()
                        );
                    });
    
    }
    
}

namespace Illuminate\Routing;
class Route
{
    public function run()
    {
        $this->container = $this->container ?: new Container;
        try {
            if ($this->isControllerAction()) {
                return $this->runController();
            }
            return $this->runCallable();
        } catch (HttpResponseException $e) {
            return $e->getResponse();
        }
    }

}

这里我们主要介绍路由相关的内容,runRoute的过程通过上面的源码可以看到其实也很复杂, 会收集路由和控制器里的中间件,将请求通过中间件过滤才会最终到达目的地路由,执行目的路由地run()方法,里面会判断路由对应的是一个控制器方法还是闭包然后进行相应地调用,最后把执行结果包装成Response对象返回给客户端。这个过程还会涉及到我们以前介绍过的中间件过滤、服务解析、依赖注入方面的信息。

相关推荐:最新的五个Laravel视频教程

위 내용은 라라벨 라우팅이 무엇인가요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.