Introduction to PHP Router
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 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:
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:
or to distinguish it from
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.
- The application receives the request, via the
routeror frontal controller.
- It decomposes the request (header) to determine the method (
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.