我在这里查看danny vankooten路由器库。看起来不错(尽管不确定如何处理从大型到大型的项目,例如电子商务网站)。现在,通过示例,这是映射
$router->map('GET','/', 'home.php', 'home');
$router->map('GET','/home/', 'home.php', 'home-home');
$router->map('GET','/plans/', 'plans.php', 'plans');
$router->map('GET','/about/', 'about.php', 'about');
$router->map('GET','/contact/', 'contact.php', 'contact');
$router->map('GET','/tos/', 'tos.html', 'tos');
假设我的网站有20-30个静态页面,或者接近50个控制器,每个控制器有2-3个动作/方法。
我如何将它们全部映射。如果使用上面的映射方法,我可能最终会超过100行,这看起来不太正确。
我相信应该有一种方法或捷径/通配符,例如检查是否有可用的页面或控制器,然后加载它或抛出404。
如何正确地绘制所有路线?
PS。向愿意回答如何使用通配符匹配控制器/方法的上述路由器的任何人提供50英镑的赏金。
您可以简化路由器文件的方法是在YAML文件中移动路由定义。您的YAML中仍然会有很多行,但可读性更高。
在您的router.php
文件中,使用以下代码:
不要忘记将symfony YAML解析器添加到您的 composer.json
use Symfony\Component\Yaml\Yaml;
$yaml_file = 'routes.yaml';
$routes = Yaml::parse(file_get_contents($yaml_file));
foreach ($routes as $route_name => $params) {
$router->map($params[0],$params[1], $params[2].'#'.$params[3], $route_name);
}
// match current request
$match = $router->match();
您的文件routes.yaml
将如下所示
index: ["GET", "/", "home_controller", "display_item"]
content: ["GET", "/content/[:parent]/?[:child]?", "content_controller", "display_item"]
article: ["GET", "/article/[:page]", "article_controller", "display_item"]
要获取较小的文件,您可以做的另一件事是将路由定义分隔为许多小的YAML文件。例如,一个用于静态文件,一个用于管理区域,一个用于前端...
要执行此操作,您必须将router.php
代码更改为以下内容:
use Symfony\Component\Yaml\Yaml;
$yaml_files = ['front.yaml', 'static.yaml', 'admin.yaml'];
foreach ($yaml_files as $yaml_file) {
$routes = Yaml::parse(file_get_contents($yaml_file));
foreach ($routes as $route_name => $params) {
$router->map($params[0],$params[1], $params[2].'#'.$params[3], $route_name);
}
}
// match current request
$match = $router->match();
Danny Van Kooten还制作PHP-Router
了对YAML文件的内置支持。(如果您查看源代码,您会发现他使用了Symfony解析器,因此这两种方法都非常相似)
YAML路由定义
base_path: /blog
routes:
index: [/index, someClass.indexAction, GET]
contact: [/contact, someClass.contactAction, GET]
about: [/about, someClass.aboutAction, GET]
Router.php
require __DIR__.'/vendor/autoload.php';
use PHPRouter\RouteCollection;
use PHPRouter\Config;
use PHPRouter\Router;
use PHPRouter\Route;
$config = Config::loadFromFile(__DIR__.'/router.yaml');
$router = Router::parseConfig($config);
$router->matchCurrentRequest();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句