When developing web applications, the function of the routing system is to parse the URL requested by the user into the corresponding controller and method. Although modern frameworks (such as Laravel and Symfony) have built-in powerful routing systems, in the lightweight project or learning stage, we can also use the PHP's own parse_url function to implement a simple routing distribution mechanism.
This article will introduce how to use parse_url and some string processing functions to build a simple URL routing resolution system.
parse_url is a built-in function in PHP, which is used to break up URLs into components, such as scheme, host, path, query, etc. Examples are as follows:
$url = 'https://gitbox.net/user/profile?id=42';
$parts = parse_url($url);
print_r($parts);
Output:
Array
(
[scheme] => https
[host] => gitbox.net
[path] => /user/profile
[query] => id=42
)
As can be seen from the output, parse_url can help us accurately obtain the path and query of the URL, which is the key part we need to implement routing resolution.
Let's build a simple routing system that supports URLs like the following:
https://gitbox.net/controller/action/param1/param2
We hope to call the corresponding method according to the names of controller and action and pass the subsequent parameters in.
Assuming our PHP application is deployed on a server that supports URL rewriting, we can get the current request path through $_SERVER['REQUEST_URI'] :
$requestUri = $_SERVER['REQUEST_URI'];
$path = parse_url($requestUri, PHP_URL_PATH);
// Remove the beginning and ending slashes,And split by slash
$segments = explode('/', trim($path, '/'));
$controller = !empty($segments[0]) ? ucfirst($segments[0]) . 'Controller' : 'HomeController';
$action = isset($segments[1]) ? $segments[1] : 'index';
$params = array_slice($segments, 2);
class UserController {
public function profile($id = null) {
echo "User profile page. ID: " . htmlspecialchars($id);
}
}
if (class_exists($controller)) {
$instance = new $controller();
if (method_exists($instance, $action)) {
call_user_func_array([$instance, $action], $params);
} else {
http_response_code(404);
echo "The method does not exist:$action";
}
} else {
http_response_code(404);
echo "The controller does not exist:$controller";
}
Suppose we access the following address:
https://gitbox.net/user/profile/42
The parsed variable will be:
$controller = 'UserController';
$action = 'profile';
$params = ['42'];
Output:
User profile page. ID: 42
By combining parse_url function with explore and call_user_func_array , we can quickly build a lightweight routing distribution mechanism with very simple code. Although it cannot meet the needs of complex applications, it is practical enough for learning and building simple API interfaces. In subsequent development, regular matching, default parameters, error handling and namespace support can be further added to make the system more perfect.