Routing plays a critical role in PHP application development. It determines which handler should process an incoming request and how the URL should be interpreted. In this article, we explore several common ways to implement routing in PHP, complete with practical code examples to guide your development approach.
This is one of the most basic methods, where conditional statements are used to check the current URI and run different logic accordingly. It’s suitable for small-scale applications or learning purposes.
$uri = $_SERVER['REQUEST_URI'];
if ($uri == '/home') {
// Home page logic
} elseif ($uri == '/about') {
// About page logic
} elseif ($uri == '/contact') {
// Contact page logic
} else {
// 404 page logic
}
As your application grows, managing routes with arrays becomes more maintainable. This method stores routing rules centrally, allowing for cleaner and more scalable logic.
$routes = [
'/home' => 'homeController',
'/about' => 'aboutController',
'/contact' => 'contactController',
];
$uri = $_SERVER['REQUEST_URI'];
if (isset($routes[$uri])) {
$controller = $routes[$uri];
// Execute logic based on $controller
} else {
// 404 page logic
}
To handle dynamic routes or more complex patterns, regular expressions are a powerful tool. This approach is ideal for applications requiring parameterized routing.
$routes = [
'/home' => 'homeController',
'/post/[0-9]+' => 'postController',
'/user/([a-z]+)' => 'userController',
];
$uri = $_SERVER['REQUEST_URI'];
foreach ($routes as $pattern => $controller) {
if (preg_match('#^' . $pattern . '$#', $uri, $matches)) {
// Execute logic using $controller and $matches
break;
}
}
Modern PHP frameworks like Laravel come with powerful built-in routing systems. These offer expressive and concise syntax to define routes and handle HTTP requests efficiently. Here’s an example using Laravel’s routing methods:
Route::get('/home', 'HomeController@index');
Route::get('/post/{id}', 'PostController@show');
Route::get('/user/{username}', 'UserController@profile');
These routes map URLs directly to controller methods, and the framework takes care of parameter parsing, middleware handling, and more advanced features.
This article introduced several common routing techniques in PHP, ranging from basic if-else structures and array mappings to regex-based routing and framework-integrated solutions. Developers should choose the approach that best suits their project’s complexity and maintainability needs. A well-designed routing system greatly improves both code clarity and application scalability.