anthonybudd / wp_route
该软件包最新版本(dev-master)没有可用的许可信息。
dev-master
2022-07-28 18:02 UTC
This package is auto-updated.
Last update: 2024-09-28 22:32:10 UTC
README
在WordPress中创建自定义路由的简单方法。
WP_Route 是在 WordPress 中创建自定义路由的简单方法,用于监听 webhooks、oAuth 回调和基本路由。WP_Route 是一个单类解决方案,无需任何设置,支持路由参数和重定向。
介绍: Medium 文章
WP_Route::get('flights', 'listFlights'); WP_Route::post('flights/{flight}', 'singleFlight'); WP_Route::put('flights/{flight}/book/{date}', 'bookFlight'); WP_Route::delete('flights/{flight}/delete', 'deleteFlight'); WP_Route::any('flights/{flight}', array('Class', 'staticMethod')); WP_Route::patch('flights/{flight}', array($object, 'method')); WP_Route::match(['get', 'post'], 'flights/{flight}/confirm', 'confirmFlight'); WP_Route::redirect('from/here', '/to/here', 301);
安装
使用 composer 安装 WP_Route
$ composer require anthonybudd/WP_Route
或者
下载 WP_Route 类并在 functions.php 文件的顶部引入它。不推荐这样做。
require 'WP_Route/src/WP_Route.php';
开始使用
只需通过调用 get()、post()、put()、patch()、delete() 或 any() 中的任何一个静态方法来定义路由。这将把指定的 URL 绑定到可调用对象。当检测到针对该 URL 的 HTTP 请求时,WP_Route 将调用该可调用对象。
WP_Route::get('flights', 'listFlights'); // http://example.com/flights function listFlights(){ // Your Code Here! }
参数
如果您需要从请求 URI 中提取路由参数,可以通过将需要提取的值用大括号包裹来实现。提取的值将被作为函数参数提供给可调用对象,如下所示。
WP_Route::get('flights/{flight}', 'singleFlight'); function singleFlight($flight){ echo $flight; // 1 }
方法
get($route, $callable)
any(), post(), put(), patch(), delete()
所有这些方法都用于将特定的路由和 HTTP 请求方法绑定到可调用对象。any() 方法将路由绑定到可调用对象,但不会限制 HTTP 方法。
WP_Route::get('flights', 'listFlights'); WP_Route::post('flights/{flight}', array('FlightController', 'singleFlight')); function listFlights(){ // Your Code Here } Class FlightController{ public static function singleFlight($flight){ // Your Code Here } }
match($methods, $route, $callable)
如果您想要将可调用对象绑定到多个 HTTP 方法,但不使用 any(),可以使用 match()。第一个参数必须是 HTTP 请求方法数组的。$route 和 $callable 参数的工作方式与 get() 相同。
WP_Route::match(['get', 'post'], 'flights/{flight}/confirm', 'confirmFlight'); function confirmFlight($flight){ // Your Code Here }
redirect($route, $redirect, $code = 301)
当用户导航到路由时,redirect() 方法将用户重定向到 $redirect 参数。要设置自定义 HTTP 响应代码,请使用第三个参数 $code。
WP_Route::redirect('open-google', 'https://google.com', 301);