How to create a router – Routing – PHP

Tram Ho

For a long time when you have used PHP framework, you have wondered: How was the route in that framework created? Today I will share with you how to create a router in PHP according to my understanding.

Project initialization.

First, I will create a project as follows:



Start with the .htaccess file first.

Function: Convert any url from / segment1 / segment2 / … to index.php? Url = segment1 / segment2 / … and return it to the server

Next is the file index.php .

At this point, call test a url we will get:

Next is the file corehttpRoute.php

Now we write the request function.

Go back to file index.php , add new code

Back to file corehttpRoute.php we write a map function for the route.

Pass the file app/routes.php

You guys try it yourself.

In case the action is a controller then we need to create a controller in the app/controllers directory. For example we create controller app/controllers/HomeController.php

and return to the app/routes.php file

You run by yourself and see the results.


So creating a router in PHP is not too difficult, right? so easy

Share the news now

Source : Viblo