The routing module of Laravel learning course, the path of laravel tutorial

Source: Internet
Author: User
Tags laravel tutorial

The routing module of Laravel learning course, the path of laravel tutorial

Preface

This article mainly introduces the related content of the Laravel routing module for your reference and learning. I will not talk about it here. Let's take a look at the detailed introduction.

Note:This article analyzes and writes the routing module code based on Laravel 5.4;

Module composition

Describes and briefly describes the relationship between each file in the routing module;


Analysis

Service Provider

Look at the Laravel module. First, find the ServiceProvider file, which is the entry to the interaction between the module and the IOC container. From this file, we can see what services the module provides to the system;

Public function register () {// register route management, which provides the routing registration and routing matching functions $ this-> registerRouter (); // register the Url generator instance $ this-> registerUrlGenerator (); // register the forwarder $ this-> registerRedirector (); // bind the PSR-7 request to implement the ServerRequestInterface interface $ this-> registerPsrRequest (); // bind the PSR-7 Response to implement the ResponseInterface interface $ this-> registerPsrResponse (); // register ReponseFactory, provides a variety of Response, such as view Response, Json Response, Jsonp Response, and file download $ this-> registerResponseFactory ();}

Route Management

The "route management" Service has the following elements to understand:

  • Route: Route. It records Url, Http Action, and Action (the specific object to be executed by the Route, which may be Closure or a method in a Controller), routing parameters, route parameter constraints;
  • RouteCollection: A Route set used to store the "box" of all Route objects ";
  • RouteGroup: A route group, which is used only during route registration. It stores some common attributes of a batch of routes, including domain, prefix, as, middleware, namespace, and where;
  • Resource: A Resource route. A Resource route is a set of routes, including the List (index), create, store, and show) display edit, update, and destory. At the same time, you can only generate some routes by calling the only or distinct T method or parameters;
  • Action: The route object to be executed. There are two forms: Closure Function and similar['uses' => 'FooController@method', 'as' => 'name']Such a string. For different representations, different processes are called during the route execution;

Registration Process

After the project is started, the loadRoutes method of all serviceproviders is executed, that is, the map method is called. Generally, the map method is as follows:

public function map(Router $router){ require __DIR__.'/routes.php';}

At this time, the project will execute a lotRoute::get,Route::post,Route::groupMethod;

When the Route: group method is used, a RouteGroup object is instantiated and put into the routing group stack header of the Router management class. Then, when a specific registered routing method such as get and post is executed, all the attributes of the current Route group Stack are merged into the new Route, and the new Route is stored in the large box of RouteCollection. When the Closure of Route: group is completed, the RouteGroup instance pull in the header will be taken out;

When you execute Route: resource, the Router management class calls the ResourceRegister class to register routes in batches;

For registration methods such as Router: get, Illuminate \ Foudation \ helpers Provides abbreviations;

  • Router::get Simplified to get,
  • Router::postSimplified to post,
  • Router::putSimplified to put,
  • Router::patchSimplified to patch,
  • Router::deleteSimplified to delete,
  • Router::resourceSimplified to resource,

Now, the RouteCollection box stores all the routes to be registered;

Request matching process

First, the request passes through the handle method of Foundation/Http/Kernel. In this method, the request executes the following statement:

$this->router->dispatch($request)

Here$this->routerIs the Router management class. The dispatch method is as follows:

Public function dispatch (Request $ request) {$ this-> currentRequest = $ request; return $ this-> dispatchToRoute ($ request);} public function dispatchToRoute (Request $ request) {// find the matched route based on the request url $ route = $ this-> findRoute ($ request ); // bind the route to the request $ request-> setRouteResolver (function () use ($ route) {return $ route ;} // trigger the RouteMatched event $ this-> events-> dispatch (new Events \ RouteMatched ($ route, $ request )); // use the Pipeline to run the middleware bound to the route and the corresponding method $ response = $ this-> runRouteWithinStack ($ route, $ request ); // set the response Header return $ this-> prepareResponse ($ request, $ response) according to the request );}

1. Find a matched route based on the request

The 'routecollect' reduces the range of routes to be matched based on the requested 'HTTP 'action. These routes are traversed in sequence, find the first Route that complies with the verification (verification is required in the 'getvalidators 'method in 'route );

2. Bind the route to the request

3. Trigger the RouteMatched event

The initialized 'laravel' project does not bind any listener to the 'routematched' route matching event. If necessary, you can customize the listener, register the event listener in the 'eventserviceprovider' of the module. Once the request matches a route, you can execute the custom method;

4. Execute the middleware bound to the route through the Pipeline and corresponding methods

In the 'runroutewithinstack' method, the system determines whether the middleware needs to be executed. if the disable' value is 'true', the middleware array to be executed is empty; otherwise, all the middleware will be found and sorted and adjusted according to 'middlewarepriority; then execute`$route->run()`Method;

5. Set the response header of the response according to the request.

Some methods used in the project

  • Obtain a route setapp('router')->getRoutes()
  • Get current request$request = app('router')->getCurrentRequest()
  • Obtain the route corresponding to the current request$ Route = $ request-> route () or $ route = app ('router ')-> getCurrentRoute ()
  • Obtain the middleware to be executed for the current route$middlewares = app('router')->gatherRouteMiddleware($route)

Url Generator

What is the Url generator?

For example,

$ Url = new UrlGenerator ($ routes = new RouteCollection, $ request = Request: create ('HTTP: // www.foo.com /')); $ url-> to ('foo/bar'); // output http://www.foo.com/foo/bar

Generate the Url of the specified path based on the current request;

These functions are completed by two files: UrlGenerator. php and RouteUrlGenerator. php. UrlGenerator. php generates a Url Based on the path name, And RouteUrlGenerator. php generates a Url Based on the route;

Common Use of columns:

Generate Based on path name

Use the to method. The first parameter is the path, the second parameter is the array, and the implode is followed by the path name. The third parameter is used to determine whether to use https.

// The path is foo/bar, and the current request's root path is http://www.foo.com, so the output is http://www.foo.com/foo/bar?url-> to ('foo/bar') // The path is foo/bar, the root path of the current request is http://www.foo.com, and the third parameter determines that scheme is https, so the output is https://www.foo.com/foo/bar?url-> to ('foo/bar', [], true) // The path name is foo/bar, and the second parameter is the supplemental path name. After implode,/baz/boom // The third parameter determines that scheme is https, therefore, the output is https://www.foo.com/foo/bar/baz/boom?url-> to ('foo/bar', ['baz', 'boom '], true) // The path is foo/bar, What are the query parameters? Foo = bar, supplemental path is/baz, so the output is https://www.foo.com/foo/bar/baz? Foo = bar $ url-> to ('foo/bar? Foo = bar ', ['baz'], true)

Generated Based on the as name of the route

The route method is used. The first parameter is the as name of the specified route, the second parameter is the parameter array, and the third parameter determines whether to display the root directory (the default value is true)

$ Route = new Route (['get'], 'foo/bar', ['as' => 'foo']); $ routes-> add ($ route ); // output 'HTTP: // www.foo.com/foo/bar?url-> route ('foo'); // The third parameter is false, indicating that the root directory is not displayed, therefore, the url in the output/foo/bar $ url-> route ('foo', [], false) // route itself does not contain parameters, then all associated arrays in the second parameter will be used as the query parameter // output/foo/bar? Foo = bar $ url-> route ('foo', ['foo' => 'bar'], false)
$ Route = new Route (['get'], 'foo/bar/{baz}/breeze/{boom} ', ['as' => 'bar']); $ routes-> add ($ route); // The url on the route carries a parameter, which is queried Based on the parameter name; the remainder is the query parameter; // The output http://www.foo.com/foo/bar/otwell/breeze/taylor? Fly = wall $ url-> route ('bar', ['boom '=> 'taylor', 'baz' => 'twel ', 'Fly '=> 'wall']); // The url on the route carries a parameter. If the corresponding parameter value cannot be found, the value is set in order. The remainder is the query parameter; // output http://www.foo.com/foo/bar/taylor/breeze/otwell? Fly = wall $ url-> route ('bar', ['taylor ', 'twell', 'fly '=> 'wall']);

Generated Based on the action name of the route

Use the action method. The first parameter is the action name of the specified route, the second parameter is the parameter array, and the third parameter determines whether to display the root directory (true by default)

$ Route = new Route (['get'], 'foo/bam ', ['controller' => 'foo @ bar']); $ routes-> add ($ route); // output http://www.foo.com/foo/bam?url-> action ('foo @ bar ');
$ Route = new Route (['get'], 'foo/invoke', ['controller' => 'invokableactionstub']); $ routes-> add ($ route ); // output http://www.foo.com/foo/invoke?url-> action ('invokableactionstub ');

Set global default parameters

$ Url-> defaults (['locale' => 'en']); $ route = new Route (['get'], 'foo ', ['as' => 'defaults', 'domain '=>' {locale} .example.com ', function () {}]); // The route url has parameters, if no parameter value is specified, the global default parameter value is displayed. The output result is http://en.example.com/foow.url-> route ('defaults ');

Set a global namespace

In this way, you do not need to omit this namespace on the action.

// Set the global namespace $ url-> setRootControllerNamespace ('namespace'); // configure to add a route $ Route = new route (['get'], 'foo/bar ', ['controller' => 'namespace \ foo @ bar']); $ routes-> add ($ route); $ route = new Route (['get'], 'foo/invoke', ['controller' => 'namespace \ invokableactionstub']); $ routes-> add ($ route ); // output http://www.foo.com/foo/bar; the value of action omitting the namespace $ url-> action ('foo @ bar '); // output http://www.foo.com/foo/invoke; the value of action omitting the namespace $ url-> action ('invokableactionstub'); // configure to add a route $ Route = new route (['get'], 'Something/else', ['controller' => 'something \ foo @ bar']); $ routes-> add ($ route ); // output http://www.foo.com/something/else; '\' is added at the beginning of the action, and $ url-> action ('\ something \ foo @ bar') is called in the global namespace ');

Forwarder

The following redirects are provided inside the forwarder;

Home

By callingapp('redirect')->home()Will jump to the root directory \;

public function home($status = 302)

Back

By callingapp('redirect')->back()The page is redirected to the previous access page; or the Global Help functionback()Yes;

public function back($status = 302, $headers = [], $fallback = false)

The third parameter indicates the page to be accessed without the previous access request. The source code is as follows:

if ($url) {  return $url;} elseif ($fallback) { return $this->to($fallback);} else { return $this->to('/');}

Refresh

By callingapp('redirect')->refresh()The current access page is refreshed;

public function refresh($status = 302, $headers = [])

To

By callingapp('redirect')->to('path')Will jump to the specified path page; or global help Functionredirect('path')Yes;

The path here does not contain the root directory, for example (foo/bar );

public function to($path, $status = 302, $headers = [], $secure = null)

The fourth parameter indicates whether to Use https;

Away

By callingapp('redirect')->away('path')Will jump to the specified path page;

Here the path contains the root directory, for example (http://xx.com/foo/bar );

public function away($path, $status = 302, $headers = [])

Secure

By callingapp('redirect')->secure('path')The page will jump to the specified path. The path here does not contain the root directory;

public function secure($path, $status = 302, $headers = [])

In essence, the to method is called.

return $this->to($path, $status, $headers, true);

Route

By callingapp('redirect')->route('route_as_name')According to the routing's as name, it will jump to the url path page consistent with the routing;

public function route($route, $parameters = [], $status = 302, $headers = [])

Action

By callingapp('redirect')->action('route_action')According to the action name of the route, it will jump to the url path page consistent with the route;

public function action($action, $parameters = [], $status = 302, $headers = [])

Guest

When you jump to the specified path page, save the current url to the session with the key name url. intended;

public function guest($path, $status = 302, $headers = [], $secure = null)

Intended

Jump to the url corresponding to the Url. intended value in the session key; if not, jump to the value passed by the first parameter;

public function intended($default = '/', $status = 302, $headers = [], $secure = null)

Response Factory)

The ResponseFactory file provides two APIs, which are related to the response type and jump;

Response

response()Will return the ResponseFactory instance;

View response

response()->view('hello', $data, 200);

Jsop response

response()->json(['name' => 'Abigail', 'state' => 'CA']);

Jsonp response

response()->json(['name' => 'Abigail', 'state' => 'CA'])->withCallback($request->input('callback'));

File response

Display the file directly in the browser instead of downloading the file, such as the sample or PDF. The first parameter of the file method is the file path, and the second parameter is the header information array;

response()->file($pathToFile, $headers);

File Download

The first parameter of the download method is the file path, the second parameter is the file name, and the third parameter is the header information array;

return response()->download($pathToFile, $name, $headers);

Jump

The jump method here actually calls the method in the jump server, but exposes more interfaces for convenient call and use;

Method Name Call Which method is actually called in the forwarder?
RedirectTo Response ()-> redirectTo (...) To METHOD
RedirectToRoute Response ()-> redirectToRoute (...) Route Method
RedirectToAction Response ()-> redirectToAction (...) Action Method
RedirectGuest Response ()-> redirectGuest (...) Guest Method
RedirectToIntended Response ()-> redirectToIntended (...) Intended Method

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.