Routing in PHP
Learn how to make a single script that serves all the URL endpoints in our application.
We'll cover the following
Why routing
As we already know, we should handle our application’s HTTP requests in a single script. At the same time, we want our application to provide different resources depending on the URL. For this, we need a router, a module that parses the request and determines which piece of code should handle it based on the predefined configuration.
Using a router
So, how do we write a router? As usual, we don’t. Although writing it could be an excellent coding practice, using an existing router library in production is better. Every framework comes with a router, and also there are several separate libraries. Usually, all the routers are very similar, and we can split the ways to use them into two categories—functional style and controller style.
Functional style routing
This style is popular in microframeworks. With this style, we list all the routes in one place and attach a handler function to each route. As an example, here’s how we can define routes for a lesson editor with the altorouter/altorouter
library:
Get hands-on with 1200+ tech skills courses.