Routing is a fundamental concept in web development that defines how an application responds to a client request for a particular endpoint (URL) and an HTTP method (GET, POST, PUT, DELETE, etc.). It's the mechanism that maps incoming URL requests to specific code or functions within your application that are designed to handle those requests.
Key Concepts and Purpose:
1. URL Mapping: At its core, routing is about taking a URL like `/products/123` and figuring out which piece of code (e.g., a controller method, a closure, or a function) should execute to process that request.
2. Clean URLs (Pretty URLs): Instead of URLs like `index.php?page=products&id=123`, routing enables user-friendly and SEO-friendly URLs like `/products/123`. This improves user experience and search engine discoverability.
3. Modularity and Organization: By centralizing route definitions, developers can clearly see all the entry points into their application. It helps in organizing code by associating specific functionalities (like fetching a user, saving a post) with distinct URLs.
4. HTTP Method Awareness: Modern routing systems can differentiate requests based on the HTTP method. For instance, `/users` with a GET request might list all users, while `/users` with a POST request might create a new user.
5. Parameters and Wildcards: Routes often include dynamic parts (parameters or wildcards) that capture values from the URL. For example, in `/products/{id}`, `{id}` is a parameter that captures the product ID from the URL.
6. Front Controller Pattern: Many routing systems, especially in MVC frameworks, rely on a "Front Controller" pattern. All requests are directed to a single entry point (`index.php`), which then dispatches the request to the appropriate handler based on the routing rules.
7. Error Handling (404 Not Found): A routing system is also responsible for identifying when no route matches the requested URL, leading to a "404 Not Found" error.
How it works (General Flow):
1. A user sends an HTTP request to a specific URL (e.g., `www.example.com/about`).
2. The web server (Apache, Nginx) is configured to direct all requests to a single PHP file, typically `index.php` (the Front Controller).
3. Inside `index.php`, a routing component analyzes the requested URL and HTTP method.
4. It compares the incoming URL against a predefined list of routes (route definitions).
5. If a match is found, the router extracts any parameters from the URL and dispatches the request to the associated handler (e.g., a controller method, a callback function).
6. The handler processes the request, interacts with the model (if applicable), and prepares a response.
7. The response is sent back to the user's browser.
Example Code
```php
<?php
/
* A very basic custom routing implementation in PHP.
* This demonstrates the core idea of mapping URLs to handlers.
*/
class Router
{
private $routes = [];
/
* Adds a GET route.
* @param string $uri The URI pattern (e.g., '/', '/users/{id}')
* @param callable $handler The function to call when the route matches
*/
public function get(string $uri, callable $handler)
{
$this->addRoute('GET', $uri, $handler);
}
/
* Adds a POST route.
* @param string $uri The URI pattern
* @param callable $handler The function to call
*/
public function post(string $uri, callable $handler)
{
$this->addRoute('POST', $uri, $handler);
}
/
* Internal method to add a route.
* @param string $method HTTP method
* @param string $uri URI pattern
* @param callable $handler Handler function
*/
private function addRoute(string $method, string $uri, callable $handler)
{
// Convert URI pattern with {param} to a regex pattern
$pattern = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<$1>[^/]+)', $uri);
$this->routes[] = [
'method' => $method,
'uri' => $uri, // Original URI for reference
'pattern' => '#^' . $pattern . '$#',
'handler' => $handler
];
}
/
* Dispatches the incoming request to the appropriate handler.
*/
public function dispatch()
{
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$requestMethod = $_SERVER['REQUEST_METHOD'];
foreach ($this->routes as $route) {
if ($route['method'] === $requestMethod && preg_match($route['pattern'], $requestUri, $matches)) {
// Extract named parameters from regex matches
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
// Remove numeric keys from params if present
foreach ($params as $key => $value) {
if (is_numeric($key)) {
unset($params[$key]);
}
}
call_user_func_array($route['handler'], $params);
return;
}
}
// No route matched
http_response_code(404);
echo '<h1>404 Not Found</h1><p>The page you requested could not be found.</p>';
}
}
// --- Usage Example ---
// 1. Create a router instance
$router = new Router();
// 2. Define routes
// Home page
$router->get('/', function () {
echo '<h1>Welcome to the Homepage!</h1>';
echo '<p>Try visiting <a href="/about">/about</a> or <a href="/user/123">/user/123</a></p>';
});
// About page
$router->get('/about', function () {
echo '<h1>About Us</h1><p>We are a simple PHP routing example.</p>';
});
// User profile page with a dynamic ID parameter
$router->get('/user/{id}', function ($id) {
echo '<h1>User Profile</h1>';
echo '<p>Displaying profile for User ID: ' . htmlspecialchars($id) . '</p>';
});
// Post submission example
$router->post('/submit', function () {
if (!empty($_POST['data'])) {
echo '<h1>Form Submitted!</h1>';
echo '<p>Received data: ' . htmlspecialchars($_POST['data']) . '</p>';
} else {
echo '<h1>Form Submission Failed</h1>';
echo '<p>No data received.</p>';
}
});
// Product page with ID and slug
$router->get('/product/{id}/{slug}', function ($id, $slug) {
echo '<h1>Product Detail</h1>';
echo '<p>Product ID: ' . htmlspecialchars($id) . '</p>';
echo '<p>Product Slug: ' . htmlspecialchars($slug) . '</p>';
});
// 3. Dispatch the request
$router->dispatch();
?>
```
To run this code:
1. Save the code as `index.php` in your web server's document root (e.g., `htdocs` for Apache, `www` for Nginx).
2. You will need to configure your web server to direct all requests to this `index.php` file. This is typically done using `mod_rewrite` for Apache or `try_files` for Nginx.
Example `.htaccess` for Apache:
```apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
```
3. Access the following URLs in your browser:
* `http://localhost/`
* `http://localhost/about`
* `http://localhost/user/123`
* `http://localhost/user/abc`
* `http://localhost/product/456/awesome-product`
* `http://localhost/non-existent-page` (should show 404)
To test the POST route, you would need to create an HTML form that submits to `/submit` or use a tool like Postman.








Routing