您好,欢迎访问一九零五行业门户网

laravel路由是什么

在laravel中,路由是外界访问laravel应用程序的通路,或者说路由定义了laravel的应用程序向外界提供服务的具体方式。路由会将用户的请求按照事先规划的方案提交给指定的控制器和方法来进行处理。
本教程操作环境:windows7系统、laravel6版,dell g3电脑。
路由是外界访问laravel应用程序的通路或者说路由定义了laravel的应用程序向外界提供服务的具体方式:通过指定的uri、http请求方法以及路由参数(可选)才能正确访问到路由定义的处理程序。
无论uri对应的处理程序是一个简单的闭包还是说是控制器方法没有对应的路由外界都访问不到他们
今天我们就来看看laravel是如何来设计和实现路由的。
我们在路由文件里通常是向下面这样来定义路由的:
route::get('/user', 'userscontroller@index');
通过上面的路由我们可以知道,客户端通过以http get方式来请求 uri "/user"时,laravel会把请求最终派发给userscontroller类的index方法来进行处理,然后在index方法中返回响应给客户端。
上面注册路由时用到的route类在laravel里叫门面(facade),它提供了一种简单的方式来访问绑定到服务容器里的服务router,facade的设计理念和实现方式我打算以后单开博文来写,在这里我们只要知道调用的route这个门面的静态方法都对应服务容器里router这个服务的方法,所以上面那条路由你也可以看成是这样来注册的:
app()->make('router')->get('user', 'userscontroller@index');
router这个服务是在实例化应用程序application时在构造方法里通过注册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调用的静态方法都对应于\illuminate\routing\router类里的方法,router这个类里包含了与路由的注册、寻址、调度相关的方法。
下面我们从路由的注册、加载、寻址这几个阶段来看一下laravel里是如何实现这些的。
路由加载
注册路由前需要先加载路由文件,路由文件的加载是在app\providers\routeserviceprovider这个服务器提供者的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这个函数在app\providers\routeserviceprovider类中,这个类继承自illuminate\foundation\support\providers\routeserviceprovider。通过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方法来处理的:
//注册路由到routecollectionprotected 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数组来创建\illuminate\routing\route类的实例:
protected function newroute($methods, $uri, $action){ return (new route($methods, $uri, $action)) ->setrouter($this) ->setcontainer($this->container);}
路由创建完成后将route添加到routecollection中去:
protected function addroute($methods, $uri, $action){ return $this->routes->add($this->createroute($methods, $uri, $action));}
router的$routes属性就是一个routecollection对象,添加路由到routecollection对象时会更新routecollection对象的routes、allroutes、namelist和actionlist属性
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); } }}
routecollection的四个属性
routes中存放了http请求方法与路由对象的映射:
[ 'get' => [ $routeuri1 => $routeobj1 ... ] ...]
allroutes属性里存放的内容时将routes属性里的二位数组编程一位数组后的内容:
[ 'get' . $routeuri1 => $routeobj1 'get' . $routeuri2 => $routeobj2 ...]
namelist是路由名称与路由对象的一个映射表
[ $routename1 => $routeobj1 ...]
actionlist是路由控制器方法字符串与路由对象的映射表
[ 'app\http\controllers\controllerone@actionone' => $routeobj1]
这样就算注册好路由了。
路由寻址
中间件的文章里我们说过http请求在经过pipeline通道上的中间件的前置操作后到达目的地:
//illuminate\foundation\http\kernelclass 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视频教程
以上就是laravel路由是什么的详细内容。
其它类似信息

推荐信息