Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does laravel routing mean

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail what laravel routing refers to. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

In laravel, routing is a way for outsiders to access Laravel applications, or routes define how Laravel applications provide services to the outside world. The route will submit the user's request to the specified controller and method for processing according to the pre-planned scheme.

The operating environment of this tutorial: windows7 system, Laravel6 version, DELL G3 computer.

Routing is the way for outsiders to access Laravel applications, or routes define how Laravel applications provide services to the outside world: the handler defined by the route can be accessed correctly through the specified URI, HTTP request method, and routing parameters (optional).

Whether the corresponding handler of the URI is a simple closure or the controller method does not have a corresponding route, they cannot be accessed by the outside world.

Today we'll take a look at how Laravel designs and implements routing.

We usually define routes in routing files as follows:

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

From the above route, we know that when the client requests URI "/ user" in HTTP GET mode, Laravel will eventually dispatch the request to the index method of the UsersController class for processing, and then return the response to the client in the index method.

The Route class used to register the route above is called Facade in Laravel. It provides a simple way to access the design concept and implementation of the service router,Facade bound to the service container. I intend to write a single blog post in the future. Here, we only need to know that the static method of calling Route corresponds to the method of router service in the service container. So you can also see the above route as registered as this:

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

The router service is bound to the service container when instantiating the application by registering the RoutingServiceProvider in the constructor:

/ / bootstrap/app.php$app = new Illuminate\ Foundation\ Application (realpath (_ _ DIR__.'/../')); / / Application: construction method public function _ construct ($basePath = null) {if ($basePath) {$this- > setBasePath ($basePath);} $this- > registerBaseBindings (); $this- > registerBaseServiceProviders (); $this- > registerCoreContainerAliases () } / / Application: register the basic service provider protected function registerBaseServiceProviders () {$this- > register (new EventServiceProvider ($this)); $this- > register (new LogServiceProvider ($this)); $this- > register (new RoutingServiceProvider ($this));} /\ Illuminate\ Routing\ RoutingServiceProvider: bind router to the service container protected function registerRouter () {$this- > app- > singleton ('router', function ($app) {return new Router ($app [' events'], $app);});})

From the above code, we know that the static methods called by Route correspond to the methods in the\ Illuminate\ Routing\ Router class, which contains methods related to routing registration, addressing, and scheduling.

Let's take a look at how these are implemented in laravel from the registration, loading, and addressing stages of routing.

Route loading

You need to load the route file before registering the route. The route file is loaded in the boot method of the server provider App\ Providers\ RouteServiceProvider:

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 first looks for the cache file of the route, and then loads the route without the cache file. The cache file is usually in the bootstrap/cache/routes.php file.

The method loadRoutes calls the map method to load the route in the route file. The map function is in the App\ Providers\ RouteServiceProvider class, which inherits from Illuminate\ Foundation\ Support\ Providers\ RouteServiceProvider. Through the map method, we can see that laravel divides the route into two large groups: api and web. The routes of these two parts are written in two files: routes/web.php and routes/api.php.

In Laravel5.5, routes are placed in several files, and the previous version is in the app/Http/routes.php file. It is easier to manage API routing and WEB routing in multiple files.

Route registration

We usually use the Facade Route to call static methods get, post, head, options, put, patch, delete. To register the route, we also said that these static methods actually call the methods in the Router class:

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);}.

You can see that the registration unification of routes is handled by the addRoute method of the router class:

/ / Register routes to RouteCollectionprotected function addRoute ($methods, $uri, $action) {return $this- > routes- > add ($this- > createRoute ($methods, $uri, $action));} / / create routes protected function createRoute ($methods, $uri, $action) {if ($this- > actionReferencesController ($action)) {/ / controller@action type routes are converted here $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;}

The third parameter passed to addRoute when registering a route action can be a closure, a string, or an array, which is similar to ['uses' = >' Controller@action', 'middleware' = >'..'] In this form. If the action is of type Controller@action, the route will be converted to an action array, and the content of the action after convertToControllerAction execution is as follows:

['uses' = >' App\ Http\ Controllers\ SomeController@someAction', 'controller' = >' App\ Http\ Controllers\ SomeController@someAction']

You can see that the complete controller class name is formed before the namespace is added to the controller name. After the construction of the action array is completed, the route is created. To create a route, you use the specified HTTP request method, URI string and action array to create an instance of the\ Illuminate\ Routing\ Route class:

Protected function newRoute ($methods, $uri, $action) {return (newRoute ($methods, $uri, $action))-> setRouter ($this)-> setContainer ($this- > container);}

Add Route to the RouteCollection after the route is created:

Protected function addRoute ($methods, $uri, $action) {return $this- > routes- > add ($this- > createRoute ($methods, $uri, $action);}

The $routes property of router is a RouteCollection object, and the routes, allRoutes, nameList and actionList properties of the RouteCollection object are updated when routing to the RouteCollection object is added.

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'])) {/ / if named, map the route object to an array value named key to make it easy to find $this- > nameList [$action [' as']] = $route } if (isset ($action ['controller'])) {$this- > addToActionList ($action, $route);}}

Four attributes of RouteCollection

The mapping of HTTP request methods and routing objects is stored in routes:

['GET' = > [$routeUri1 = > $routeObj1.].]

The contents stored in the allRoutes attribute program the contents of a two-digit array in the routes property after an one-digit array:

['GET'. $routeUri1 = > $routeObj1 'GET'. $routeUri2 = > $routeObj2.]

NameList is a mapping table of route names and route objects

[$routeName1 = > $routeObj1.]

ActionList is a mapping table between route controller method strings and route objects

['App\ Http\ Controllers\ ControllerOne@ActionOne' = > $routeObj1]

In this way, the route is registered.

Routing addressing

In the article on middleware, we said that the HTTP request arrives at the destination after the pre-operation of the middleware on the Pipeline channel:

/ / 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);}

As you can see in the above code, the destination of Pipeline is the closure returned by the dispatchToRouter function:

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

The dispatch method of router is called in the closure, and routing addressing occurs in the first phase of 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 is responsible for finding the route. This function is responsible for matching the route and binding the url parameter of request to the 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) {/ / after finding a matching route, assign the path parameter binding in URI to the route (if any) 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 ()); the value in the routes attribute generated in the registered routing phase is loaded first, and the routes stores the mapping between the HTTP request method and the routing object.

Then call the matches method of the routing object in this heap, the matches method, and the matches method will verify the HTTP request object. The corresponding Validator is: UriValidator, MethodValidator, SchemeValidator, HostValidator.

The rules of the route are converted to regular expressions in $this- > compileRoute () before validation.

UriValidator mainly depends on whether the URI of the request object matches the regular rules of the route:

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 verifies the request method, SchemeValidator verifies whether the protocol is correct (http | https), and HostValidator verifies the domain name. If the host attribute is not set in the route, this verification will not be performed.

Once a route has passed all the authentication, it will be returned. Next, assign the path parameter binding in the request object URI to the route parameter:

Routing parameter binding

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 ($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;});}

The process of routing addressing after the assignment of routing parameters is completed, and it is time to run and return the response object by matching the corresponding controller method in the route.

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 / / collect middleware applied in routing and controller $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 () }}}

Here we mainly introduce the content related to routing. Through the source code above, we can see that the process of runRoute is actually very complicated. It collects the route and the middleware in the controller, filters the request through the middleware before it finally reaches the destination route, executes the run () method of the destination route, and determines whether the route corresponds to a controller method or a closure, and then calls it accordingly. Finally, the execution result is packaged as a Response object and returned to the client. This process also involves information about middleware filtering, service parsing, and dependency injection that we have previously introduced.

This is the end of the article on "what does laravel routing mean?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report