moxie-leean/wp-endpoint

此包已被废弃,不再维护。作者建议使用 moxie-lean/wp-endpoint 包。

wp-endpoint

0.3.0 2016-04-19 16:24 UTC

This package is auto-updated.

Last update: 2022-02-01 12:56:41 UTC


README

一个类,使得创建新的WordPress端点更加容易。

默认情况下,端点位于 leen 命名空间下,版本号为 1。这些数据可以使用下面指定的任何过滤器进行覆盖。

该类提供了一系列定义好的方法和机制来注册一个新的端点,这使得定义新的端点的过程非常直接。

入门

通过终端使用 composer 是安装此包最简单的方法

composer require moxie-leean/wp-endpoint

或者通过在您的 composer.json 文件中添加以下行

"require": {
  "moxie-leean/wp-endpoint": "dev-master"
}

这将从 packagist 站点 下载文件,并将您设置为使用仓库 master 分支上的最新版本。

之后,您可以包含 autoload.php 文件,以便在对象创建时自动加载类。

include '/vendor/autoload.php';

用法

在您的模块中添加依赖项后,您需要创建一个新的类来定义您的端点,例如

<?php
use Leean\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 Lean\Endpoints;

use Leean\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,用于对集合项目进行自定义格式化。