nolte / wp-endpoint
wp-endpoint
3.0.2
2021-12-16 05:09 UTC
Requires
- php: >=7.4 || >=8.0
Requires (Dev)
README
一个类,它使得创建新的WordPress端点更加容易。
默认情况下,端点位于leen命名空间下,版本号为1。这些数据可以使用下面指定的任何过滤器进行覆盖。
该类提供了一套定义的方法和机制来注册新的端点,这使得定义新的端点的过程相当直接。
入门指南
安装此包的最简单方法是使用终端中的Composer
composer require nolte/wp-endpoint
或者在你的composer.json文件中添加以下行
"require": { "nolte/wp-endpoint": "dev-master" }
这将从packagist站点下载文件,并将您设置为使用存储库master分支上的最新版本。
之后,您可以包含autoload.php文件,以便在对象创建过程中自动加载类。
include '/vendor/autoload.php';
使用方法
在您的模块中添加依赖项后,您需要创建一个新的类来定义您的端点,例如
<?php use Nolte\AbstractEndpoint; class customEndpoint extends AbstractEndpoint { protected $endpoint = '/customEndpoint'; public function endpoint_callback( \WP_REST_Request $request ) { $data = [ 'data' => 'Hi', 'count' => 10, 'id' => $request->get_param( 'id' ) ]; return $this->filter_data( $data ); } public function endpoint_args() { return [ 'id' => [ 'required' => true, 'sanitize_callback' => function ( $id ) { return absint( $id ); }, ], ]; } }
在这个类中,您有
init或您想要公开的任何其他名称是一个公共静态方法,它始终具有相同的签名,以执行运行新端点的代码。endpoint_callback,默认情况下,您有一个方法允许您定义端点的GET请求的响应,GET是默认的HTTP动词。endpoint_args,与endpoint_callback相同,是默认的回调,允许您定义端点是否允许参数以及如何使用。endpoint_options,如果您想指定一组新的HTTP动词或重写默认端点选项,您只需要返回一个包含端点所需参数的数组。
例如,为了定义一个新的slug参数,使用不同的HTTP动词并重用默认的get参数,您只需要定义如下
protected function endpoint_options() { return [ [ 'methods' => \WP_REST_Server::DELETABLE, 'callback' => [ $this, 'custom_callback_now' ], ], parent::endpoint_options, ]; }
parent::endpoint_options将返回在Endpoint类上定义的默认选项,如果您不想为GET请求重新声明选项。
集合
还有可供集合使用的抽象类。
<?php namespace Nolte\Endpoints; use Nolte\AbstractCollectionEndpoint; class MyCollection extends AbstractCollectionEndpoint { protected $endpoint = '/my-collection'; protected function loop() { $data = []; $this->query = new \WP_Query( $this->args ); while ( $this->query->have_posts() ) { $this->query->the_post(); $data[] = $this->query->post; } wp_reset_postdata(); return [ 'data' => $data, 'pagination' => $this->get_pagination( $this->query->found_posts, $this->query->max_num_pages ) ]; } }
过滤器
nolte_endpoints_api_namespace,这允许您覆盖API定义上使用的默认命名空间。nolte_endpoints_api_version,这个过滤器允许您更改API的版本号。nolte_endpoints_data_${api},其中${api}是您的端点名称,例如在上面的例子中:nolte_endpoints_data_customEndpoint。nolte_endpoints_collection_item,用于对集合项目进行自定义格式化。