kilahm / attribute-router
一个使用用户定义属性来定义单页应用程序路由的 Hacklang 路由器。
Requires
- hhvm: >=3.5
- hackpack/hack-class-scanner: 1.*
- kilahm/hack-clio: 1.1.0
Requires (Dev)
- hackpack/hackunit: 0.3.*
This package is not auto-updated.
Last update: 2024-09-24 01:38:12 UTC
README
一个使用用户定义属性来定义单页应用程序路由的 Hacklang 路由器。
安装
更新您的 composer.json
文件,在 required
块中包含以下行。
“kilahm/attribute-router”: “dev-master”
使用
定义属性
要将方法与 HTTP 路径关联,可以将属性与该方法关联。
<<route('get', '/a')>> public static function getA(Container $c, Vector<string> $matches) : void { ... }
属性 route
必须至少有一个参数,但可以有多个。如果有两个参数,则第一个必须是 HTTP 动词(get
、post
、put
或 delete
),第二个是用于测试路径的正则表达式。如果第一个参数不在上述列表中,则该路径将路由到该方法,适用于任何动词。
如果只有一个参数存在,则该单个参数被视为正则表达式,动词默认为 any
。
注意,路由编译器将在您的模式周围添加字符串开头锚点和字符串结尾锚点。所以如果您的模式是 /path/a
,则路径 /path/ab
不会路由到该方法。
所有路由方法必须是公共的、静态的,并且必须接受恰好两个参数。第一个由您定义,但所有路由方法必须具有相同的方法签名。第二个是字符串向量,它是通过在您在属性中定义的正则表达式上使用 preg_match
返回的匹配集合。第一个参数预期是某种类型的 IOC 容器,以允许方法开始实例化所需的服务。
编译
通过属性定义了所有您喜欢的路由后,您必须运行编译脚本
vendor/bin/scanroutes path/to/search other/path/to/search [--exclude /path/to/exclude [--exclude /other/path/to/exclude ...]]
您可以指定多个基本路径进行搜索和多个要忽略的路径。所有搜索路径都将递归搜索。
调用 vendor/bin/scanroutes --help
以获取所有选项的列表。
Routes.php 和 AutoRoutes.php
运行路由编译脚本后,您的项目目录(或如果使用了 --install-to
,则为安装目标目录)中应有两个文件。AutoRoutes.php
文件是您的路由处理程序的代理方法的集合。
Routes.php
文件存在,这样您就可以在不使用属性进行注释的情况下添加路由。按照文件中给出的模式手动添加路由。
如果再次运行 scanroutes
,它不会覆盖 Routes.php
文件。这意味着如果您在运行编译器之前已经创建了这样的文件,则路由器类可能不会正常工作。
实例化
您的应用程序引导文件应实例化您的 IOC/DI 容器,然后将它传递给 AutoRoutes
的一个实例。然后,您必须将 AutoRoutes
的实例传递给 Router
。必须这样做,因为路由器类不知道容器的类。只有生成的 Routes
和 AutoRoutes
类知道容器的类。
// bootstrap $container = new Container(); $router = new kilahm\AttributeRouter\Router(new AutoRoutes($container)); $app = new App($container, $router); // Pass the router and container to your main application class $app->run(); // Or however your application class works...
或者,您可以创建一个工厂来为您进行实例化和注入(这也是您最初拥有 IOC/DI 容器的原因)。
class Container { public function makeRouter() : \kilahm\AttributeRouter\Router { return new \kilahm\AttributeRouter\Router(new AutoRoutes($this)); } }
匹配
要实现路由魔法,只需在您的 Router
对象上调用 match
方法即可。
$path = $_SERVER['REQUEST_URI']; // Or any other way to get the path to match // Somehow determine which HTTP verb was used to access this resource $router->match($path, HttpVerb::Get); // Or the appropriate verb
要查看支持的完整HTTP动词列表,请参阅HttpVerb.php。还要参阅枚举文档,以充分利用此功能。
示例
<<route('/pattern/(.*)/(.*)')>> public static function patternA(Container $c, Vector<string> $matches) : void { // If the original path was /pattern/foo/bar, then // $matches[0] is ‘/pattern/foo/bar’ // $matches[1] is ‘foo’ // $matches[2] is ‘bar’ }
上述路由将针对任何HTTP动词被调用,并且$matches
向量将填充由preg_match
在模式上匹配的结果。
<<route(‘delete’, ‘/user’)>> public static function deleteUser(Container $c, Vector<string> $matches) : void { // $matches == Vector{‘/user’} }
上述路由仅针对HTTP DELETE调用被调用。请注意,$matches
向量包含单个条目,即完全匹配的路由。