Other Parts:
By default, PHP routing follows file-based routing, where URLs are structured as /page-1.php
. However, the custom router we will develop will enable a cleaner URL structure such as /page-1/subpage
. This system will also allow us to utilize parameterized URLs like: /post/slug
, resulting in a more professional and user-friendly appearance.
How does it work
The .htaccess
file we created earlier will assist us in redirecting all routes to the index.php
file. Afterward, we can extract the URI from the $_SERVER
superglobal variable. For instance, when we visit: /some-page
, we can retrieve the route by accessing $_SERVER['REQUEST_URI']
. This allows us to display the appropriate content associated with that particular URI.
Create the basic Router
This code will check what the URI is about
. If so, it will require the about.view.php
file (which contains the About page content).
Build the Advanced Router MVP
For advanced and complex usage, relying solely on basic routing might not be efficient. In such cases, we can create a Router
class to handle incoming URIs more effectively. I have built a router that resembles Laravel's routing approach, where we can define routes and match them against incoming requests. If a match is found, we can then require the corresponding controller (although, for now, we can directly use views at this stage).
This approach will provide more flexibility and scalability for handling various routes and their corresponding actions or controllers.
How does it work
To begin with, we can create an array to store our routes. At the end of the file, we will execute a route
method to check if the URI matches any defined routes, and if a match is found, we can render the associated view. This approach allows for a clear separation of routes and view rendering.
Code time
Note: The router class will be a singleton
Let's update index.php
Let's add some routes to web.php
Let's add the views. We will need four views:
-
Home:
home.view.php
-
About:
about.view.php
-
Contact:
contact.view.php
-
404:
404.view.php
(We will put it insideErrors
directory later)
Conclusion.
In this section, we learned how to build a basic routing system. We previously discussed setting up the environment to handle this routing, which you can review in the First Step section. However, this basic router is limited and does not account for handling different HTTP methods. To overcome this limitation, we will need to introduce controllers, which will handle the logic and determine the appropriate view for each route and method.
See you in the next one!