DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on • Edited on

What are the steps to build a basic PHP router?

In my last project, I have a direct mapping between a file path , address bar and a controller. If I visit contact well, I have contact.php in address bar and sure enough contact.php in controller directory. But I want to change all of that.
Instead I want a single point of entry where I can be responsible for mapping whatever is in URI to the corresponding controller.

what is router in PHP?

In PHP, a router is a component that plays a crucial role in handling HTTP requests and routing them to the appropriate controllers or handlers. It acts as a central dispatcher, directing incoming requests to the relevant code that processes the request and generates a response.

Basic steps to build router

  • Firstly you have to make a directory named controller and then grab the previous project files about,index and control.php
    and then paste these in it.

  • Next you have to create a file functions.php that stores information about different functions working stored inside it .
    In this a function dd(); dump and die is used. Dump in PHP is used to get multiple outputs of single variable and is in human readable form.

<?php

function dd($value)
{
    echo "<pre>";
    var_dump($value);
    echo "</pre>";

    die();
}

function urlIs($value) {
    return $_SERVER['REQUEST_URI'] === $value;
}

Enter fullscreen mode Exit fullscreen mode

As the dd(); function is completed then next function is checked according to the value that is given to it. It checks the equality of value and request URL and then passes to superglobal variable `$_SERVER.
The next step is to check the route of desired value and move the user to its destination.

Routes corresponding to the value

Here is to initialise the routes for the desired URLs in code. As when user taps contact in menu bar move user to contact screen, show output there. Different routes are available here for router to locate and go to desired one.

`php
<?php
$uri = parse_url($_SERVER['REQUEST_URI'])['path'];
$routes = ['/' => 'controllers/index.php',
'/about' => 'controllers/about.php',
'/contact' => 'controllers/contact.php',
];
function routeToController($uri, $routes) {
if (array_key_exists($uri, $routes))
{require $routes[$uri];
} else {
abort();
}
}
function abort($code = 404) {
http_response_code($code);
require "views/{$code}.php";
die();
}
routeToController($uri, $routes);

`

  • If the user enters a wrong value or hits the tab whose data is not present in main file then it moves the user to file 404.php which shows 404 error page to user with text link in blue colour "Go to Home Page".

php
<?php require('partials/head.php') ?>
<?php require('partials/nav.php') ?>
<main>
<div class="mx-auto max-w-7xl py-6 sm:px-6 lg:px-8">
<h1 class="text-2xl font-bold">Sorry. Page Not Found.</h1>
<p class="mt-4">
<a href="/" class="text-blue-500 underline">Go back home.</a>
</p>
</div>
</main>

While the remaining code of last project will remain same to show an output screen that contains a TabBar with icon, button, logo and profile picture etc.
Routers typically performs the task of route mapping and generates the url to move user to the corresponding controller page or screen.
I hope that you have understand it.

Top comments (4)

Collapse
 
zubairmohsin33 profile image
Zubair Mohsin

Good job on the post.

To handle the styling of code blocks properly, refer to this cheatsheet: github.com/adam-p/markdown-here/wi...

Collapse
 
ghulam_mujtaba_247 profile image
Ghulam Mujtaba

I made the changes, but code is not displaying properly as snippets.

Collapse
 
zubairmohsin33 profile image
Zubair Mohsin

Hmm, try putting more spaces between the paragraph and the code snippets.

<?php require('partials/head.php') ?>
<?php require('partials/nav.php') ?>
<main>
<div class="mx-auto max-w-7xl py-6 sm:px-6 lg:px-8">
<h1 class="text-2xl font-bold">Sorry. Page Not Found.</h1>
<p class="mt-4">
<a href="/" class="text-blue-500 underline">Go back home.</a>
</p>
</div>
</main>
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
ghulam_mujtaba_247 profile image
Ghulam Mujtaba

I also added spaces between code and paragraph but no change occurred.