How to load a class based on a pretty URL in a Model View Controller (MVC) page
Question: How to load a class based on Dynamically expanding controller with new category composed of pretty URLs?
Solution:
To resolve this issue, the following steps need to be taken:
Here is sample code for dynamically loading a class against a pretty URL:
// 注册自动加载器 spl_autoload_register(function ($name) { $path = 'path/to/classes'; $filename = $path . '/' . $name . '.php'; if (file_exists($filename)) { require $filename; return true; } return false; }); // 使用路由表匹配 URL $routes = [ '/{resource}/foobar' => ['controller' => 'FoobarController', 'action' => 'index'], '/{resource}' => ['controller' => 'ResourceController', 'action' => 'show'], ]; $url = $_SERVER['REQUEST_URI']; foreach ($routes as $pattern => $route) { if (preg_match($pattern, $url, $matches)) { $controller = $route['controller']; $action = $route['action']; break; } } // 调用控制器方法 if (isset($controller) && isset($action)) { $controller = new $controller; $controller->$action($matches); } else { // Handle 404 }
The above is the detailed content of How to Dynamically Load Classes Based on Pretty URLs in an MVC Framework?. For more information, please follow other related articles on the PHP Chinese website!