Introduction to PHP Router
Learn how to handle user requests and call the appropriate file (content).
We'll cover the following
Our application works quite well. However, it’s not professional yet. This is because we’re calling the corresponding file in the URL for each page request. This is a problem. Let’s see why.
The problem
The way that our application is handling the HTTP request is not very smart:
- The URI is not elegant.
- It allows for security issues since we’re revealing the internal structure of our files.
Let’s take an example of the projects list
URI:
local.tracker.com/controllers/project_list.php
As we can see, the URI is too long and passes the exact path to the file.
We would prefer for our code to be simple like we see on many sites or applications:
local.tracker.com/list
or to distinguish it from tasks list
:
local.tracker.com/projects/list
Here, we’re no longer directly calling any file in the URI.
The solution: routing
Simply speaking, the routing consists of mapping an HTTP request to a request handler, which can be a function or a method.
Let’s take an example and break it down so that we can understand how the routing system works.
local.tracker.com/list
- The application receives the request, via the
router
or frontal controller. - It decomposes the request (header) to determine the method (
GET
,POST
…), path, host, and so on. - The application will look for a defined route that matches the request.
- Once found, it will take the defined action and return a response to the user.
As we can see from the steps listed above, we need to create a router and redirect all the requests there.
Although in a real-world application, we’ll need to use a robust routing system like that of Symfony, in this course, we’ll build the system from scratch so that we learn how routing works in most frameworks.
We defined a GET route for the /list
URI which returns a response when, when a user calls it. In our case, it returns the list view.
Get hands-on with 1400+ tech skills courses.