Download the PHP package tenjuu99/wp-resta without Composer
On this page you can find all versions of the php package tenjuu99/wp-resta. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download tenjuu99/wp-resta
More information about tenjuu99/wp-resta
Files in tenjuu99/wp-resta
Package wp-resta
Short Description WordPress REST Api development framework using DI
License GPL-2.0-or-later
Informations about the package wp-resta
Wp\Resta
WordPress 上で REST API 開発をするためのプラグインです。
アイデアやインターフェースは BEAR.Sunday から影響を受けています。
How to install
前提: WordPress 管理画面からパーマリンク設定を「投稿名」などにしておいてください。
自作テーマで利用する
functions.php
で初期化
以下は、サンプルのディレクトリにあるAPIを読みこむ設定です。
プラグインで利用する場合
WordPress のプラグインとしても利用できます。
次の例は composer/installers
を利用して WordPress プラグインを wp-content/plugins/
以下に配置しています。
無事 wp-content/plugins 以下に展開できたら、管理画面からプラグインを有効化してください。
Example
インストールしたら、管理画面に REST API doc
というメニューが追加されます。
このページでは、 Swagger UI を使ってAPI定義をドキュメント化しています。
このサンプル実装は src/REST/Example/Routes/
以下にあります。
How to develop
自分のルーティング定義を追加するためには、 functions.php
での初期化時のコードにルーティング用ディレクトリの設定を記述してください。
routeDirectory
に渡す配列は、 ['ディレクトリ名', 'php namespace', 'api namespace']
となっています。
schemaDirectory
は ['ディレクトリ名', 'php namespace']
です。
必要に応じて composer.json
にも autoload 設定を追加してください。
src/Routes/HelloWorld.php
を作ります。
次のURLが生成されます。
"Hello, world!" と値が返ってきていることを確かめてください。
URL定義とURL変数
myroute
が functions.php
で定義した namespace ですが、 helloworld
にはクラス名がそのまま利用されています。
URL 定義は ROUTE
定数を定義することで変更できます。ついでにURL変数も定義してみます。
次のURLが生成されるとおもいます。
"Hello, amashige!"
と返ってくるとおもいます。
ROUTE定数のなかに [var]
と []
で囲えばパスパラメータとして扱うことができます。
変数は次のようなパターンを許容します。
これらは、ROUTE定数に user/[id]
のような形でURL埋め込み変数として定義されていればパスパラメータとして機能します。
パスパラメータとして利用されていないが URL_PARAMS
に定義されている変数はクエリパラメータとして利用されます。
次のような例は、 http://example.com/wp-json/myroute/user/2?name=tenjuu99
として展開されます。
これらの変数は callback メソッドで受け取ることができます。
コールバック
AbstractRoute
を継承したクラスが callback
という名のメソッドを持っている場合、このメソッドを呼びだしてレスポンスの body にします。body として返してよいのは、 WP_REST_Response
が body として解釈できるものになります。また、Psr\Http\Message\ResponseInterface
を返した場合にはそのまま利用されます。
callback
メソッドの引数は、URL変数を受けとることができます。 URL変数
に id
を定義していれば callback(int $id)
と定義して問題ありません。
また、簡易な DI があるため、解決可能なクラスを引数に定義すると受け取ることができます。ランタイムに値が決まるもの(例えば WP_REST_Response
)などはコンストラクタインジェクションでは値が決まっていませんが、コールバックが呼び出される時点では確定しているので、利用できます。
DI
簡易なDIを用意しています。
基本的には autorwiring で、ほとんどの場合に設定なしで利用できます。
また、基本的にはコンストラクタインジェクションのみ対応しています(AbstractRoute::callback
は例外)。
Bar::get
の返り値が解決されます。
上記は DI の autowiring で解決可能ですが、interface を注入する場合は自動で解決できません。この場合は設定が必要になります。
設定は、初期化コードに dependencies
を渡すことができます。
また、autowiring 機構はクラスやインターフェースの依存しか解決しないため、コンストラクタがクラスやインターフェース以外の値を受けている場合は解決できません。 この場合は関数を使ってください。