CodeIgniter 中国开发者社区诚征热爱 CI 的版主

查看完整版本: kohana文档翻译(Routing)

星期八 2008-7-16 15:30

kohana文档翻译(Routing)

一般情况下,URL一一对应控制器的类和方法,例如
[indent]http://www.example.com/class/function/arg1/arg2
[/indent]第一段对应控制器类,第二段对应方法,其余的对应方法的参数,然而有时候你希望改变这种行为,比如你希望用这样的URL:[url=http://www.example.com/article/22]www.example.com/article/22[/url],这里第二段是一个数字,它是控制器的一个参数,并非一个方法,那么Kohana的URL路由功能可以改变这一切.
[b]Kohana的路由设置[/b]
你需要从system/config拷贝一份routes.php 到application/config目录,
默认情况,routes.php包含两条规则
[code=PHP]$config['_allowed'] = '-a-z 0-9~%.,:_';[/code]

$config['_allowed']决定了URL中允许的字符,不在这个范围的字符串不能被程序接受

[code=PHP]$config['_default'] = 'welcome';[/code]

$config['_default']指定默认URL路由,它用来指示当URL中没有分段时,将要调用的控制器类,例如,在浏览器输入[url=http://www.example.com/]www.example.com[/url],welcome控制器将会被使用,虽然它不被包含在URL中,其结果相当于[url=http://www.example.com/welcome]www.example.com/welcome[/url]
[b]指定你自己的路由[/b]
除了上面默认的路由外,你也可以指定你自己的路由规则,基本的路由规则格式如下:
[code=PHP]$config['route'] = 'class/method';[/code]

route是你需要路由的参数,class/method会替换掉它
例如,你的程序在[url=http://www.example.com]www.example.com[/url],有如下路由规则,
[code=PHP]$config['test'] = ‘foo/bar’;[/code]
你在浏览器中输入[url=http://www.example.com/test]www.example.com/test[/url],你将会看到[url=http://www.example.com/foo/bar]www.example.com/foo/bar[/url]的内容.
[b]利用正则表达式[/b]
路由部分其实是一个正则表达式,如果你不熟悉正则表达式,你可以在[url=http://www.php.net/manual/en/reference.pcre.pattern.syntax.php][color=#63dbf5]PHP WEBSITE[/color][/url]访问,采用正则表达式可以使你的URL更有选择性的配对路由规则,举例说明:如果你想要URL:[url=http://www.example.com/article/22]www.example.com/article/22[/url]被访问,我们可以这样设置URL路由.$config['article/([0-9]+)’] = ‘news/show/$1′;它将配对以article开头后面跟着数字的URLS,对于这种格式的URL,将会采用news控制器,访问show()方法,article number 将作为show()方法的参数,在[url=http://www.example.com/article/22]www.example.com/article/22[/url]中相当于访问[url=http://www.example.com/news/show/22.]www.example.com/news/show/22.[/url]
[b]捷径[/b]
除了采用正则表达式外,还有两种捷径:

[list][*]:any 配对任意非空字符[*]:num 配对任意数字[/list]它们可以用于正则表达式的场合,前面的例子[url=http://www.example.com/article/22]www.example.com/article/22[/url]路由到[url=http://www.example.com/news/show/22]www.example.com/news/show/22[/url], 我们可以用如下的路由规则来代替:
[code=PHP]$config['article/(:num)'] = 'news/show/$1';[/code]

这样看起来更加直观

[[i] 本帖最后由 星期八 于 2008-7-16 15:32 编辑 [/i]]

flyy 2008-7-18 12:35

:victory: 希望继续,感觉比ci更全面!
页: [1]
查看完整版本: kohana文档翻译(Routing)