我在这里看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解析器,因此两种方法非常相似)
来自doc
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();