moxie-lean / wp-endpoint
2.0.0
2016-05-31 15:03 UTC
Requires
- php: >=5.4
Requires (Dev)
README
一个类,使创建新的WordPress端点更加容易。
默认情况下,端点位于leen命名空间下,版本号为1。这些数据可以使用下面指定的任何过滤器进行覆盖。
该类提供了一套定义方法,以及注册新端点的机制,使得定义新端点的过程非常简单。
入门
安装此包的最简单方法是使用终端中的composer
composer require moxie-lean/wp-endpoint
或者在你的composer.json
文件中添加以下行
"require": {
"moxie-lean/wp-endpoint": "dev-master"
}
这将从packagist站点下载文件,并将你设置到位于存储库master分支的最新版本。
之后,你可以包含autoload.php
文件,以便在创建对象时自动加载类。
include '/vendor/autoload.php';
使用方法
在你模块中添加依赖项后,你需要创建一个新类来定义你的端点,例如
<?php
use Lean\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方法或重写默认端点选项,你只需要返回一个包含端点所需参数的数组。
例如,为了定义一个具有不同HTTP方法的新slug参数并重用默认的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 Lean\Endpoints;
use Lean\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
)
];
}
}
过滤器
ln_endpoints_api_namespace
,这允许你覆盖API定义中使用的默认命名空间。ln_endpoints_api_version
,此过滤器允许你更改API的版本号。ln_endpoints_data_${api}
,其中${api}
是你的端点名称,例如在上面的示例中:ln_endpoints_data_customEndpoint
。ln_endpoints_collection_item
,用于为集合项执行自定义格式化。