How to load classes in MVC-like pages based on pretty URLs?
When building a custom MVC website, you often need to deal with dynamic URLs, where the URL path represents an action to be performed within the application. A common challenge is how to map different parts of the URL to controller methods.
Problem
To dynamically expand the categories in the blog controller, you can use the following steps:
Answer
One way to implement this functionality is:
// 正则表达式模式匹配 URL 路径 $pattern = '/^(?<controller>\w+)\/(?<method>\w+)\/(?<param>\w+)$/'; // 获取解析结果 $matches = preg_match($pattern, $url, $matches); // 自动加载控制器类 $class = '\Controller\' . $matches['controller']; $controller = new $class(); // 调用控制器方法 $controller->{$matches['method']}($matches['param']);
This method allows you to combine any number of categories Dynamically added to the blog controller without modifying the controller itself.
The above is the detailed content of How to Load Classes in an MVC Framework Using Pretty URLs?. For more information, please follow other related articles on the PHP Chinese website!