downshiftorg/wp-router

WordPress 插件和主题的简单路由器

6.0.0 2022-02-03 19:14 UTC

This package is auto-updated.

Last update: 2024-08-29 03:21:02 UTC


README

一个简单的基于查询字符串参数的域路由器。

虽然这个库现在可以在 WordPress 之外使用,但它的主要目的是在 WordPress 生态系统中使用,作为添加自定义路由而不需要特定页面脚本的手段。

用法

路由器将 get 或 post 请求与响应者匹配。响应者是一个函数或可调用的类。

use DownShift\WordPress\Router;

$router = new Router('my_scope');

// matches ?my_scope=/myroute
$router->post('/myroute', function () {
  // do something here
});

// listen terminates via exit after route function executes
$router->listen();

您还可以为路由定义提供一个可调用的类。

$router->post('/myroute', new InvokableClass());

// or a string if you prefer
$router->post('/myroute', 'DownShift\Responders\SomeClass');

服务注入

路由函数中的服务使用 PHP 5.3 兼容版本的 Illuminate Container 进行解析。

$container = new Container();
$container->bind('SomeInterface', 'SomeImplementation');
$router = new Router('my_scope');
$router->bind($container);

$router->get('/test', function (SomeInterface $service) {
  // do a thing with $service
});

如果解析一个类,构造函数将具有依赖注入。仅当使用字符串时,类的解析才有效。

测试

测试是用 peridot 编写的,可以像这样运行

vendor/bin/peridot