路由
StartMVC的默认路由都是自动的,系统会根据URL自动载入指定的模块、控制器和操作方法,并传入参数。如果路由不做配置的话,系统会调用默认路由方式。
路由配置(支持多种方式)
按优先级处理路由规则(正则 > 内置模式 > 普通匹配)
普通字符串匹配
['about', 'home/page/about'],
内置路由模式:
//简便方法
//(:any)代表任意字符
//(:num)代表纯数字
//(:alpha)代表纯字母
//(:alphanum)代表字母+alphanum
return
[
['(:any)','home/$1'],//隐藏home模块url(适用于单模块)
['article_(:num)','article/detail/$1'], //格式为/article_232.html
['category/(:num)','category/index/$1'],//格式为/category/232.html
['tag/(:any)','tag/$1'],//格式为/tag/中国.html
['user/(:alphanum)/profile', 'user/profile/view/$1'],
['api/users/(:num)', 'api/user/get/$1'] //REST风格路由
];
自定义正则表达式路由:
配置的原理其实就是正则替换,它返回一个数组,每个数组元素就是一条规则。这个数组由两个元素组成,第一个是路由改写后的URL正则表达式,第二个是路由需要改写的原URL。
// config/route.php
return
[
['/^about$/', 'home/index/about'], // about 等于 home/index/about
['/^article\/(\d+)$/', 'home/index/article/$1'] // article/2 等于 home/index/article/2
['/^category\/(.*?)$/','home/category/index/$1'],
['/^about$/', 'home/index/about'],
['/^column\/(\d+)$/', 'home/index/column/$1']
// 匹配 article/123 到 home/index/article/123
['/^article\/(\d+)$/', 'home/index/article/$1']
// 匹配 blog/tech/456 到 blog/post/view/tech/456
['/^blog\/(\w+)\/(\d+)$/', 'blog/post/view/$1/$2']
];