primal/路由

此包已被废弃,不再维护。未建议替代包。

基于文件的URL路由引擎

2.0 2013-05-10 23:22 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:21:26 UTC


README

#Primal Routing

由Jarvis Badgley创建并版权所有于2013年,chiper at chipersoft dot com。

Primal Routing是PHP 5.3及以后版本的简洁URL路由类,基于以下四个原则

  1. 每个路由都是一个文件
  2. 正斜杠是一个段分隔符,而不是一个层次
  3. 匹配段最多的路由获胜。
  4. 任何段都可以有对应的值

##路由匹配

以下URL作为一个例子

http://localhost/alpha/beta/charley/delta

上述请求被解析成一个参数列表。Primal Routing然后逆向工作,扫描您的路由文件夹,寻找第一个与段列表匹配的文件(使用点分隔文件名)。在这种情况下,它将按以下顺序搜索以下文件

  1. alpha.beta.charley.delta.php
  2. alpha.beta.charley.php
  3. alpha.beta.php
  4. alpha.php
  5. _catchall.php
  6. _notfound.php

注意,最后两个路由可以使用 ->setNotFound()->setCatchAll() 函数进行更改。

它找到的第一个匹配项将被执行。如果没有找到与请求URL匹配的路由,则它将查找一个通配路由,最后调用一个文件未找到路由(如果不存在 _notfound 处理程序,则抛出异常)。

##路由参数

不是路由名称部分的段在调用路由时传递,按其顺序索引。所以如果上述URL匹配到 alpha.beta.php,则路由将接收以下参数数组

Array
(
    [0] => charley
    [1] => delta
)

现在让我们看看原则 #4,每个段都可以有对应的值。检查以下URL

http://localhost/alpha=1/beta=foo/charley=0/delta=/echo

此URL将匹配到相同的路由,但配对的段将作为参数可用

Array
(
    [alpha] => 1
    [beta] => foo
    [charley] => 0
    [delta] =>
)

注意,enableEmptyArgumentInclusion() 选项将导致所有段作为参数包含,空段为null。

###站点索引

URL /http://my.domain.com/ 被Primal Routing解释为对站点索引的调用。Primal Routing将尝试路由到 "index"(通过 setSiteIndex() 调整此值)然后传递到文件未找到路由 ("_notfound")。站点索引不能接收参数,除非URL以站点索引名称开头。示例

http://my.domain.com/index/foo=bar

##演示

如果您已安装Composer和PHP 5.4,您可以通过在repo根目录中运行以下命令来查看Primal Routing的实际操作

composer dump-autoload
php -S localhost:8000 demo.php

这将创建一个临时的服务器在您的电脑上。尝试以下URL

##运行测试

您必须安装Composer和PHPUnit才能运行单元测试。从repo根目录运行以下命令

composer dump-autoload
phpunit

##服务器转发

在标准配置中,Apache和Nginx只有在您直接访问时才会调用包含Primal Routing代码的文件。以下配置假定 index.php 包含Primal Routing初始化代码。

###Apache

将以下内容放入虚拟主机目录定义中,或者放入您的网站根目录的 .htaccess 文件中。

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule ^$ index.php	[L]

# forward all requests to /
RewriteRule ^$ index.php [L]

# send all other requests to index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteRule ^/?.*$ index.php [L]
</IfModule>

注意,Apache必须配置mod_rewrite才能使此功能正常工作。

###Nginx

将以下内容放入虚拟主机 server 块中。

location = / {
    rewrite ^ /index.php last;
}

location / {
    if (!-e $request_filename) {
        rewrite ^ /index.php last;
    }
}

请注意,此配置假设您已通过传统方式通过FastCGI接口配置了PHP。还可能需要将以下内容添加到您的PHP位置指令中

try_files $uri $uri/ $uri/index.php /index.php;

##许可证

Primal Routing采用MIT许可证发布。无需署名。详情请参阅所附LICENSE文件。