haruncpi/wp-api

优雅的WordPress REST API路由系统

v1.0.1 2023-12-15 05:42 UTC

This package is not auto-updated.

Last update: 2024-09-20 09:23:25 UTC


README

优雅的WordPress REST API路由系统。

WP API

支持

Buy Me A Coffee

文档

安装

composer require haruncpi/wp-api

配置

在您的插件初始化文件中,编写以下简单的配置代码。

ApiConfig::set_route_file( __DIR__ . '/api-routes.php' )
		->set_namespace( 'MyPlugin\Api' )
		->init();

路由定义

打开 api-routes.php 文件并编写路由

语法

ApiRoute::get( $prefix, $endpoint, $callback, $auth = false );
ApiRoute::post( $prefix, $endpoint, $callback, $auth = false );

// Multiple route in a prefix group.
ApiRoute::prefix( $prefix, function( ApiRoute $route ) {
    $route->get( $endpoint, $callback, $auth = false );
    $route->post( $endpoint, $callback, $auth = false );
});

位置

  • $prefix 是您的插件名称加上api版本。例如: myplugin/v1
  • 默认情况下, $auth 为false表示端点可以不经过认证访问。
  • 要使端点 secure,请在$auth的位置传递一个回调函数。

示例

ApiRoute::get( 'myplugin/v1', '/me', 'ApiController@me' );

安全路由

ApiRoute::get( 'myplugin/v1', '/me', 'ApiController@me', 'AuthController@check' );

编写回调函数的多种方式。

ApiRoute::get( 'myplugin/v1', '/me', 'ApiController@me' );
ApiRoute::get( 'myplugin/v1', '/me', array( ApiController:class, 'me' ) );
ApiRoute::get( 'myplugin/v1', '/me', array( 'MyPlugin\Api\ApiController', 'me' ) );
ApiRoute::get( 'myplugin/v1', '/me', function() {
    // Do something.
});

多路由注册

ApiRoute::prefix( 'myplugin/v1', function( ApiRoute $route ) {
    $route->get( '/products', 'ApiController@products' );
    $route->get( '/categories', 'ApiController@categories' );
});

带有认证检查

// With auth check
ApiRoute::prefix( 'myplugin/v1', function( ApiRoute $route ) {
    $route->get( '/me', 'ApiController@me' );
    $route->get( '/settings', 'ApiController@settings' );
    $route->post( '/logout', 'ApiController@logout' );
})->auth( 'AuthController@check' );

插件示例

API Plugin 是此Composer包的WordPress示例插件。