How can PHP URL routing be implemented without using frameworks like CakePHP?
PHP URL routing can be implemented without using frameworks like CakePHP by creating a custom routing system using PHP. This can be achieved by parsing the requested URL, identifying the controller and action based on the URL parameters, and then executing the corresponding controller method. This allows for custom routing logic to be defined within the PHP code itself.
// Custom URL routing implementation
$url = $_SERVER['REQUEST_URI'];
// Parse the URL to extract controller and action
$parts = explode('/', $url);
$controller = isset($parts[1]) ? $parts[1] : 'home';
$action = isset($parts[2]) ? $parts[2] : 'index';
// Include the controller file and execute the action method
$controllerFile = 'controllers/' . $controller . '.php';
if (file_exists($controllerFile)) {
require_once($controllerFile);
$controllerInstance = new $controller();
if (method_exists($controllerInstance, $action)) {
$controllerInstance->$action();
} else {
echo 'Action not found';
}
} else {
echo 'Controller not found';
}