Why use a router in PHP

When I first started learning PHP, I didn't quite understand the benefits of using a Router.

Typically, as a beginner learning PHP, you link the URI to the file name. Meaning if I had a URI uhded.com/about.php then I would make an about.php file. If I had uhded.com/contact.php I would create a contact.php file, and so on.

This above works fine for smaller websites but it can start to become a hassle on larger projects and that's where using a router becomes obvious.

Here are a couple of examples you might want to use a router.

  • What if you don't want to name the file exactly the same as the route? For example, if you want uhded.com/about to map to a file /views/team-members.php. With a router, you would define this route and make it possible.

  • What if you want to see all your routes in a central location? Now you can have a dedicated routes file where you can define and see all your routes.

  • If a user enters a route that doesn't exist, you will have an easy way to define a 404 page. In your routes file if the user is trying to go somewhere that's not defined you can easily handle it (typically with a 404 page).

  • You no longer have to include the .php extension in the URI. If a user enters uhded.com/contact in your routes file you would define that "contact" maps to the file views/contact.php.

  • In a larger project, what if you want to handle authorization, authentication, etc all from one place? Instead of duplicating the same code in each file. You can set up checks in the router file.

    For example, if a user tries to access routes that are only for logged in users. You can group these routes together and include the proper validation in one place instead of doing this in every file.

  • What if you have a nested file structure like /products/category/item/x etc but you want to map this to a short and sweet URI like /item/x. Very easy to set this up in your router file.

This is a great reason why a Framework is a great tool to use. Frameworks (like Laravel) have all this set up for you so you know all the routes are in one file.

If you want to set up your own router, here is a simple PHP route article.

Or you can watch this free Laracast episode where the instructor sets up a Router from scratch.

Make one page websites quickly using my Carrd Templates