PHP:MVC - Model View Controller | Routing of Controllers & Routers #2

Prince

[ Verified Seller ]
Staff member
Trusted Seller
Joined
11 yrs. 6 mth. 27 days
Messages
5,381
Reaction score
18,380
Age
45
Wallet
11,590$
Introduction:

In this part we'll get into the routing of the front controller. So let's go back to our front controller's class:

Code:
Please, Log in or Register to view codes content!
What we need to do now is to start routing the routes that have been added. So we need to make a check whether the key of a route is positioned in the beginning of the URI:

Code:
Please, Log in or Register to view codes content!
f that returns TRUE than we have the namespace we inquire where $v is the namespace itself. So we need to write that namespace somewhere. Let's make a property for it:

Code:
Please, Log in or Register to view codes content!
And since I just though right now, we need to extend the idea for the routes by differentiating the URL parameter from the controller. So back to our routes.php file we gonna add keys to the array so as to map them correspondingly.

Code:
Please, Log in or Register to view codes content!
So now in this case, we should also modify the front controller to get that:

Code:
Please, Log in or Register to view codes content!
Suppose we request the following URL after the modifications we've made so far:

Code:
Please, Log in or Register to view codes content!
And replace it with the following:

Code:
Please, Log in or Register to view codes content!
If a namespace is not found and the default router is existent (which in our case is ['*']) so then, the namespace itself would be equal to the default one. As simple as that. The other situation is when a router is not registered as well but as well as that, there is no default router for it to be compared/appended to, it throws an error.

Executing and echoing out the result like so sums up in the following:

Code:
Please, Log in or Register to view codes content!
We get the default one once more. Same would be if we register a new route. Suppose this one would be 'admin'.

Code:
Please, Log in or Register to view codes content!
We've developed the code previously as I said, so before you start asking why we're not elaborating into it now, refer to the previous series. Though I'll put it as plain as possible right now. Basically, we are exploding the URI. If the 0 parameter exists that's our controller in fact and the first parameter is the method. If there is no method, we grab the default one and if there is no controller we take the default controller and the default method as a whole.
 
Top Bottom