netrivet/wp-router

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

6.0.0 2022-02-03 19:14 UTC

This package is not auto-updated.

Last update: 2024-09-14 17:05:53 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