Routing is an important link in project development, each project will use routing management interface, the next article will take you to learn routing from the source.
preface
Due to the length of the article, the executive will write in a new article.
I explained the following in my last post.
- Simple analysis of route identification
- Let’s talk about the facade by defining the route
- $this->group = $this->group = $this->group = $this->group
- Routing rule preprocessing
- Quick access to parse generated route identifiers
But there’s a lot more to be said about routing, and we’ll look at the following.
- Routing parameters
- Variable rules
- Resource routing
- Route configuration (that is, in the return in the route file)
- Dispatch at the beginning of understanding
- Route-check Checks URL routes
- .
Let’s go through them one by one.
Also put a routing diagram for your reference.
1. Routing parameters and variable rules
Again, the code starts here, but this time the focus is on routing parameters and variable rules.
These two points are simply to show you the use and simple implementation process.
Deeper understanding will not go to explain, because these two points in the peacetime development process is not much use.
Remember you in the file thinkphp/library/think/route/RuleItem. We’ve seen about routing parameters in PHP to use!
The documentation also provides many supported parameters, as shown in the figure below.
How does this route parameter work?
Then use the route we used before, and set up the URL suffix detection, support matching multiple suffixes.
So we set up the route should be how to access!
If the access is based on normal routing rules, an error will be reported. Please continue to see the correct access mode.
The request of the correct address should be http://www.source.com/index.php/hello/1.html, that is, on the request address need to joining together we set the suffix HTML.
The specific execution process of this piece can be simply looked at by using the code tracker, which will not be demonstrated here.
I’m just going to show you an example of the routing parameter, and I’m pretty much done.
Global routing parameter
The last section of route parameters describes global route parameters.
Go straight to the document and you’ll see it.
Here click set two routing rules for testing, one optional, one mandatory, and set the routing rule to add file suffixes.
The address requested when passing parameters.
Request address without passing parameters.
That’s what I wrote for the route parameters.
Did not go to do special deep explanation, basically is to explain how to use, there is the existence of this thing, so understand.
Variable rules
The same variable rule, which is even less available in kaka’s daily development work.
The only benefit of the variable rule is to filter the parameters.
That is, a variable rule is a behavior that exists only when the routing rule has parameters.
Ka-ka here to provide you with a simple case.
Demonstration case
The pattern parameter is appended to the route
So let’s see how this request is written.
If the argument is a number, you can print the argument passed in.
But an error is reported when a letter is passed in.
Therefore, variable rules are the filtering of parameters after routing rules, that is, they are processed by using regex.
So far, the rules for routing parameters and variables are brief.
Although the content is very simple, most of them are use cases to introduce how to use, without going to the source code.
The first peacetime development is not how to use.
Second, further understanding is needed in this paper. Here is just an understanding.
In fact, it is estimated that there are still many people do not understand why the input routing address can appear internal content, this later will be in-depth understanding.
Second, resource routing
Setting up the resource routing is also simple.
It is also convenient to use the command line to create files.
The created controller is itself a resource routing file.
The resource method of the Route file is then executed again.
This method also has routing rules, routing addresses, routing parameters, and variable rules.
Then will come to thinkphp/library/think/route/Resource. PHP class
Do some simple property assignments in time in this class.
Then there is the place where the kaka circle comes out, and then the kaka circle will explain the place.
Because of the resource class inherits the RuleGroup class so they will jump to thinkphp/library/think/route/RuleGroup PHP class.
Go to the action that this method performs.
- Route rules are simply processed. If a route has parameters, route rules need to be converted to
Blog / / < < name > or blog name? >
- $this->parent $this->parent
object(think\route\Domain)
, need to route the first section of the article, section 3, and assign fullName in this step. - The last step is to assign a routing rule to the fullName.
Then go back up and see what’s next.
Setting routing rules for groups After processing, some attributes are assigned, mainly the following three.
- Routing variable rule
- Routing parameters
- REST routing method definitions
There is nothing more to attribute assignment than to understand what the corresponding attribute does.
This is followed by a return of the class instance with the request key value $this and a check to see if the route method is annotated.
The result comes back clattering out for a quick look, not all of it, but you know what the value is.
After the above execution, the lazy method is returned to the upper layer
First of all, we know what this parameter is passed in: does the route delay resolution
And then you get to the lazy method
ParseGroupRule is called in this method, and the argument passed in is the routing rule for the group
This is all about routing grouping, so I’m not going to talk about it here.
Until now that’s all I have to say about resource routing
Finally, click will draw the executive brain map for you
When was the domain name set up
$this->parent->getDomain() $this->parent->getDomain()
This line of code is known to get the requested domain name based on the method name
But does everyone know where this domain name is set up?
When you request the resource Route, the constructor of the Route class is executed
There is a line of code inside the constructor to get the requested domain name
I’m going to go to the host method
In the host method, this parameter is true
$this->server(‘HTTP_HOST’) $this->server(‘HTTP_HOST’)
As you can see at the second point in the ka-ka circle, the first condition is true, but the second condition is not true
$this->host = $this->host
$this->host; $this->host; $this->host;
This is followed by the initialization of the default domain name method
That’s where the domain name is initialized
Will there be any questions at this time is clearly is in thinkphp/library/think/route/Resource. PHP execution inside this class!
Set the domain name address is in thinkphp/library/think/Route. The PHP in this class!
About this one think can understand because of inheritance relationship!
So here for the setting of this domain name should be very clear, if you do not understand to look at the article written by kaka!
It takes hours to write an article, but you can only read it in a few minutes. What can you read in a few minutes?
To the code slowly, want quality, not efficiency ha!
So this is the end of the explanation of when the domain name is set up, and then the routing configuration – array configuration interpretation
4. Route configuration – Array configuration interpretation
In fact, I think a lot of people here will be a little confused.
Most of them don’t understand what it means. Where is it?!
In fact, this configuration was only available after 5.1, and did not exist in previous versions.
This configuration location is actually the Route we have been learning, did not expect it! That’s how powerful it is.
It is the return in the routing configuration.
Review the loading of routing files!
The first is the entry file, of course.
The click circles will return this instance of App. If you don’t understand, go to the container article.
So this line of code will execute to the run method of the App class.
Then came to thinkphp/library/think/App. PHP run method of this class to look at.
What you can see directly is the initialization application.
Go to the initializer application and see about route initialization
Let’s go to the routeInit method
When importing a route configuration, you need to make a judgment about it. The judgment is based on the array configuration in the route configuration file.
This should give you some idea of when the routing configuration is loaded.
However, there is nothing in the documentation about configuring routing in arrays, which means there is no use case.
Therefore, we need to trace according to the import method.
Find out how to use it directly.
$this->route->import($rules); This line of code, kaka is doing an interpretation.
$this->route ($this->route);
The first thing we need to know is that the App class inherits from the Container class
Then there are a few magic methods at the end of the Container class.
The __get magic method is executed when the Route class does not exist in the App.
The make method in the __get magic method is then executed.
About this method, kaka said no less than three times, you can go to the article on containers ha!
Road, and then continue our march came to thinkphp/library/think/Route. The import of PHP configuration file routing rules, the method of import
You can see several familiar variable rules in this method
So let’s do a simple test with these values
Just as resource routing was described in section 2, it’s time to test using checking resource routing as a condition
The resource routing configuration must be disabled, otherwise the test cannot be performed
Make an interview at this time
Yes, that’s it. That’s how easy it is to use
Array routing is the same as resource routing, only in the order in which it is executed
Routing rules are ultimately passed to the Resource method through a loop as well
The same method is executed
This section will briefly talk about here, mainly is to have a certain understanding of the route initialization needs
And learn how to configure routing arrays
This approach was not used very often, or at all, in previous releases, 5.1 or 6.0
This is just to remind you of the route initialization process, and what array configuration routes actually do, okay
Where there is a problem, solve it, not leave it unresolved
5. Dispatch initial recognition and Route-Check detection of URL routes
This piece of content is in the implementation of the application, next to take you to a brief understanding.
There is no source code explanation for this section, but it is intended for later use, so it is important to know what dispatch is all about.
The following figure shows the process of going back to the upper layer to continue after route initialization.
And then it goes to route detection here.
The routing test uses the following figure
We can then print this scheduling information
The relevant values for dispatch have been printed out in the figure above
A brief preview of the routeCheck method will follow
In the above method, just make it clear that the cache is handled at this step and a Dispatch object is returned.
This piece of the source code we can simply take a look, is not very important.
Route-check Checks URL routes
But this one needs to be looked at briefly.
Before we look at this, we need to make sure that we know what the two parameters we passed in are.
Parameter 1: route rule Parameter 2: Check whether mandatory routes are configured
Once you know what the parameters mean, you need to go to the check method to find out.
In this method for automatic detection of domain name routing let’s print out what the data looks like.
In fact, the result of this is the same as before resource route mount,
Then through the pathinfo separator: put in the url / | instead
In addition, the system checks whether the routes match exactly in the configuration file
The final execution uses default route resolution
There are too many details about the routing. If we go to details one by one, it will take a lot of time.
So that’s it, just know what was done and what was returned.
How is the request class found
$result = $domain->check($this->request, $url, $completeMatch) This is going to be executed.
I don’t care what this method does.
Instead, you need to care if the $this->request is found and executed.
The first thing you can see is that there is a request attribute in the Route class.
Then come to the Route constructor, where you’ll find new ground.
ArrayAccess is used to access objects like an array, but there is no request property in $app, so it executes the __get magic method in the container class. In the __get method, it calls the make method in the container. The first argument is request. Eventually, an instance of Request will be returned.
Here $app is actually an app instance injected through dependency injection.
The App class inherits from the Container class, the Container class.
There are several magic methods at the bottom of the container class.
Focus only on the __get method here.
A function that the __get method executes when accessing nonexistent attributes.
This means that you will eventually execute the make method.
This method returns an instance of the Request through a series of operations.
And store this instance in the container, the next time to use directly can be retrieved.
The make method in the container class is particularly important in the container class and is also the soul method.
The entire framework instance is returned through the container, so the importance of this method cannot be overstated.
Kaka previously had a particularly deep understanding of containers and presented it in the form of an article.
Detect domain name routing
Draw the flow for you first, and then follow the rhythm of the flow.
One of the first things to ensure is that the domain name routing is performed in the execution application.
The upper level execution process is in the entry file.
So the first thing that this code is going to execute into is routeCheck, so let’s look at this file.
The explanation for this method is URL routing detection.
In this method, the route Cache is checked first, which is about Cache.
The most important of these methods is that route detection returns a Dispatch object.
So this is the next one.
The first thing to be clear about is what the two parameters are passed in.
- $path : string(4) “blog”
- $must : bool(false)
The following things are done in detecting URL routes.
- Pathinfo separator: put in the url / | instead
- Whether the routes match completely
- Detecting Domain name Routing
- Default Route Resolution
The next step is to conduct in-depth analysis of the domain name routing process.
The first two implementations are just string manipulation, just to see what’s returned.
Also make clear the meaning of three parameters in the execution of detecting domain name routing.
- $this->request: $this->request: $this->request: $this->request: $this->request: $this->request: $this->request: $this->request: $this->request: $this->request
Article of section 6
- $url : string(4) “blog”
- $completeMatch: Whether the route matches exactly
$result = $domain->check($this->request, $url); That’s the point of this section.
The following processes are performed in this method, and the important execution processes are analyzed in depth.
- CheckRouteAlias: checkRouteAlias
- Check the URL binding: checkUrlBind
- Determining route Parameters
- Adding Domain Name Middleware
- Check packet routes: parent::check
CheckRouteAlias: checkRouteAlias
Parameter interpretation
- $request: an instance of the request class
- $URL: The blog that was passed
There are two things that need to be clarified in this method
- Strpos: Finds the position of the first occurrence in the string
- STRSTR: STRSTR returns a pointer to the position where string2 first appears in string1, STRSTR (“Helloworld! ,”world”); ? >\n output: \nworld!
- The URL address is processed first: the blog is returned
- Gets the alias route definition NULL
- For example, resource routing blog returns false
There is a method in detecting route aliases that needs to be looked at again
The argument is the blog passed in above
Came to this method, must first clear thing is this method in the class thinkphp/library/think/Route. In PHP
And this class uses all classes under Think \route
This method takes the blog that has been routed from the detection and retrieves it from the Alias property in the Route class, or returns NULL if it doesn’t exist
The use of this alias is described below
Coming to the end of detecting aliased routes return $item? $item->check($request, $url) : false; That’s this line of code, and as you can see from the figure above, this item is NULL
And finally return the NULL back.
Check the URL binding: checkUrlBind
Parameters that
- $request: an instance of the request class
- $URL: The blog that was passed
In this method, only the places that come out of the click circle below are detailed.
Go to the method getBind to read the route binding and you can see that ka-ka has printed out the parameters passed in.
This method is in thinkphp/library/think/route/Domain. The PHP class – This class, remember the routing rules set $This – > group is to use This class, do not know can go to the routing of the article in the first quarter.
In this method, the current subDomain is fetched once.
At the end of this method, the WWW will be returned. Look at the first section circled.
The host method in the Request class is used to get the current domain name and then split it.
Array (1) {[0] =>\n String (3) “WWW “\n}
$this->subDomain $this->subDomain
Return Final result Return subdomain: WWW
It then goes back to the upper level, where it determines the current subdomain name WWW.
Some are all judgment processing, the first judgment is definitely not true, because it only returns WWW, it doesn’t.
The following check is based on the route binding, so it is necessary to know that NULL is always returned.
Knowing that NULL is returned at the bottom level, the judgment here will also not be true, so the result returned to the upper level will be false.
Determining route Parameters
According to the above process execution will eventually return to thinkphp/library/think/route/Domain. PHP this Domain routing check methods.
Then start judging the route parameters.
No route parameter is skipped.
Route parameters exist: execute method setRouteVars: Set the route variable. This parameter is only available in framework 5.1.5 and older, so it will not be explained in detail.
Adding Domain Name Middleware
About the middleware here is not its explanation, because the later will open a new article to explain, this article is still focused on routing ha!
Detection packet routing
Return parent::check($request, $URL, $completeMatch);
Will jump to the class file: thinkphp/library/think/route/RuleGroup. PHP, because Domain classes are inherited RuleGroup of this class.
Parameters that
- $request: an instance of the request class
- $URL: The blog that was passed
- $completeMatch: Whether the route matches exactly
In this method ka-ka will only elaborate on one of the processes here, merging group parameters.
Because this method is also the main thread through the execution process, the rest of the methods are all checking, judging.
Nine,
There are two articles on routing, and I haven’t finished reading the source code for a long time. The routing section is the most complex and difficult to understand.
The class is a ring of a ring, routing first temporarily understand here, later in the reading of other source code in other content supplement.
In this routing paper, the main implementation of the flow chart you must look carefully.
The group attribute that is used to register the routing rule returns the Domain class, which must be clear.
You need to know the process of configuring domain names in routes and when domain names are configured.
The return array in the routing file and the process of importing the routing file should be clear.
Then I’ll go back to ArrayAccess, which accesses objects like arrays.
Container magic method __get method, in this magic method there is a make method, mainly used to return an instance of a class, and stored in the container.
About the aspect of routing temporarily said here, is expected to have a route will be finished.
Adhering to learning, blogging and sharing is the belief that Kakha has been upholding since she started her career. I hope you can get a little help from my articles on the Internet. I’m Kaka. See you next time.