라라벨 라우팅이 무엇인가요?
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('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } }
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['router']->getRoutes()->refreshNameLookups(); $this->app['router']->getRoutes()->refreshActionLookups(); }); } } protected function loadCachedRoutes() { $this->app->booted(function () { require $this->app->getCachedRoutesPath(); }); } protected function loadRoutes() { if (method_exists($this, 'map')) { $this->app->call([$this, 'map']); } } } class Application extends Container implements ApplicationContract, HttpKernelInterface { public function routesAreCached() { return $this['files']->exists($this->getCachedRoutesPath()); } public function getCachedRoutesPath() { return $this->bootstrapPath().'/cache/routes.php'; } }
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(['GET', 'HEAD'], $uri, $action); } public function post($uri, $action = null) { return $this->addRoute('POST', $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 = ['uses' => $action]; } if (! empty($this->groupStack)) { $action['uses'] = $this->prependGroupNamespace($action['uses']); } $action['controller'] = $action['uses']; return $action; }
注册路由时传递给addRoute的第三个参数action可以闭包、字符串或者数组,数组就是类似['uses' => 'Controller@action', 'middleware' => '...']这种形式的。如果action是Controller@action
类型的路由将被转换为action数组, convertToControllerAction执行完后action的内容为:
[ 'uses' => 'App\Http\Controllers\SomeController@someAction', 'controller' => 'App\Http\Controllers\SomeController@someAction' ]
可以看到把命名空间补充到了控制器的名称前组成了完整的控制器类名,action数组构建完成接下里就是创建路由了,创建路由即用指定的HTTP请求方法、URI字符串和action数组来创建IlluminateRoutingRoute
AppProvidersRouteServiceProvider< /code>이 서버 공급자의 부팅 방법에 로드됨:<p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>protected function newRoute($methods, $uri, $action)
{
return (new Route($methods, $uri, $action))
->setRouter($this)
->setContainer($this->container);
}</pre><div class="contentsignin">로그인 후 복사</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>protected function addRoute($methods, $uri, $action)
{
return $this->routes->add($this->createRoute($methods, $uri, $action));
}</pre><div class="contentsignin">로그인 후 복사</div></div></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['as'])) { //如果时命名路由,将route对象映射到以路由名为key的数组值中方便查找 $this->nameList[$action['as']] = $route; } if (isset($action['controller'])) { $this->addToActionList($action, $route); } } }
경로 등록이 라우터 클래스의 addRoute 메서드에 의해 처리되는 것을 볼 수 있습니다.
[ 'GET' => [ $routeUri1 => $routeObj1 ... ] ... ]
Controller@action
유형의 경로인 경우 액션 배열로 변환됩니다. ConvertToControllerAction이 실행된 후 액션의 내용은 다음과 같습니다. 🎜[ 'GET' . $routeUri1 => $routeObj1 'GET' . $routeUri2 => $routeObj2 ... ]
IlluminateRoutingRoute
클래스: 🎜 [ $routeName1 => $routeObj1 ... ]
[ 'App\Http\Controllers\ControllerOne@ActionOne' => $routeObj1 ]
//Illuminate\Foundation\Http\Kernel class Kernel implements KernelContract { protected function sendRequestThroughRouter($request) { $this->app->instance('request', $request); Facade::clearResolvedInstance('request'); $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('request', $request); return $this->router->dispatch($request); }; } }
$destination = function ($request) { $this->app->instance('request', $request); return $this->router->dispatch($request); };
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; } }
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; } }
class UriValidator implements ValidatorInterface { public function matches(Route $route, Request $request) { $path = $request->path() == '/' ? '/' : '/'.$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('request', $request); Facade::clearResolvedInstance('request'); $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('request', $request); return $this->router->dispatch($request); }; } }
上面代码可以看到Pipeline的destination就是dispatchToRouter函数返回的闭包:
$destination = function ($request) { $this->app->instance('request', $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() == '/' ? '/' : '/'.$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(), '/'.$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('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() ); }); } } 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Laravel 이메일 전송이 실패 할 때 반환 코드를 얻는 방법. Laravel을 사용하여 응용 프로그램을 개발할 때 종종 확인 코드를 보내야하는 상황이 발생합니다. 그리고 실제로 ...

laravel 일정 작업 실행 비 응답 문제 해결 Laravel의 일정 작업 일정을 사용할 때 많은 개발자 가이 문제에 직면합니다 : 스케줄 : 실행 ...

Laravel의 이메일을 처리하지 않는 방법은 LaRavel을 사용하는 것입니다.

DCAT를 사용할 때 DCATADMIN (LARAVEL-ADMIN)에서 데이터를 추가하려면 사용자 정의의 테이블 기능을 구현하는 방법 ...

Laravel 프레임 워크 및 Laravel 프레임 워크 및 Redis를 사용할 때 Redis 연결을 공유하는 데 영향을 줄 수 있습니다. 개발자는 문제가 발생할 수 있습니다. 구성을 통해 ...

Laravel 다중 테넌트 확장 패키지 패키지 패키지 패키지 패키지 Stancl/Tenancy, ...

Laraveleloquent 모델 검색 : 데이터베이스 데이터를 쉽게 얻을 수 있습니다. 이 기사는 데이터베이스에서 데이터를 효율적으로 얻는 데 도움이되는 다양한 웅변 모델 검색 기술을 자세히 소개합니다. 1. 모든 기록을 얻으십시오. 모든 () 메소드를 사용하여 데이터베이스 테이블에서 모든 레코드를 가져옵니다. 이것은 컬렉션을 반환합니다. Foreach 루프 또는 기타 수집 방법을 사용하여 데이터에 액세스 할 수 있습니다 : Foreach ($ postas $ post) {echo $ post->

7 백만 레코드를 효율적으로 처리하고 지리 공간 기술로 대화식지도를 만듭니다. 이 기사는 Laravel과 MySQL을 사용하여 7 백만 개 이상의 레코드를 효율적으로 처리하고 대화식지도 시각화로 변환하는 방법을 살펴 봅니다. 초기 챌린지 프로젝트 요구 사항 : MySQL 데이터베이스에서 7 백만 레코드를 사용하여 귀중한 통찰력을 추출합니다. 많은 사람들이 먼저 프로그래밍 언어를 고려하지만 데이터베이스 자체를 무시합니다. 요구 사항을 충족시킬 수 있습니까? 데이터 마이그레이션 또는 구조 조정이 필요합니까? MySQL이 큰 데이터로드를 견딜 수 있습니까? 예비 분석 : 주요 필터 및 속성을 식별해야합니다. 분석 후, 몇 가지 속성만이 솔루션과 관련이 있음이 밝혀졌습니다. 필터의 타당성을 확인하고 검색을 최적화하기위한 제한 사항을 설정했습니다. 도시를 기반으로 한지도 검색
