アノテーションを使用したphp api restフレームワークと Swagger 2.0 のサポート。
Composer を使用して依存関係を管理し、PHP-API-REST をダウンロードします。
composer require diomac/php-api-rest
API フォルダーの例:
.htaccess ファイル:
RewriteEngine On
RewriteCond %{REQUEST_URI} !init.php$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* init.php [L,QSA]
init.php ファイル:
use DiomacAPIApp;
use DiomacAPIAppConfiguration;
/**
* Initializing API configuration
*/
$config = new AppConfiguration();
$config->setBaseUrl('/php-api-rest/example/v1');
/**
* Adding resources classes
*/
$config->addResource(examplev1ExampleResource::class);
$config->addResource(examplev1ExampleSwaggerJson::class);
/**
* Execute API
*/
try{
$app = new App($config);
$app->exec();
}catch (Exception $ex){
...
}
namespace example;
use DiomacAPIResource;
use DiomacAPIResponse;
use DiomacAPIUnauthorizedException;
class ExampleResource extends Resource
{
...
}
/**
* @method get
* @route /auth/usr-data/id/{id}
* @guard(
* className="examplecoresecureExampleGuard",
* @parameters(operationId="GETUSERDATA")
* )
*/
function getUsrData()
{
// ... your code
$this->response->setCode(Response::OK); // set HTTP response code
$this->response->setBodyJSON($jsonSerializable); // set responde data
return $this->response; // return response object
}
次のメソッドを備えた DiomacAPIRequest オブジェクト:
$this->request->getParams() // returns the parameters of the URL and $_GET
$this->request->getData() // returns an object sent by the front end
$this->request->getRoute() // returns the executed route
$this->request->getMethod() // returns the executed HTTP method
DiomacAPIResponse オブジェクトとメソッド:
$this->response->setHeader('name', 'value'); // set HTTP header response
$this->response->setCode(Response::BAD_REQUEST); // set HTTP response code
$this->response->setBody('string'); // set response body
$this->response->setBodyJSON(JsonSerializable object); // set response body to convert in JSON
$this->response->setContentType(''); // set content type response (for setBodyJSON not needed)
そして、DiomacAPIResource クラスからメソッドを継承します。
$this->getRoute(); // returns the configured route
$this->getParams(); // returns the parameters of the URL and $_GET
$this->getParam('name'); // returns a parameter by name
return $this->response;
APIの取得メソッド:
/**
* @method get
* @route /example/v1/pet/{petId}
*
* @return Response
* @throws Exception
*/
function getPet(): Response
{
try {
$petId = $this->getParam('petId');
$pet = new Pet($petId);
/**
* API Rest best practices - selecting returned fields and aliases
*/
$fields = $this->getParam('fields');
if($fields){
Response::setFields(explode(',', $fields), Pet::class);
}
$this->response->setCode(Response::OK);
$this->response->setBodyJSON($pet);
} catch (Exception $ex) {
throw new Exception('Internal Server Error', Response::INTERNAL_SERVER_ERROR);
}
return $this->response;
}
/**
* @method get
* @route /auth/usr-data/id/{id}
* @guard(
* className="examplecoresecureExampleGuard"
* )
* @guard(
* className="examplecoresecureExampleGuardWithParams",
* @parameters(operationId="GETUSERDATA", operationName="GETUSERDATA")
* )
*/
function getUsrData()
{
// ... your code
$this->response->setCode(Response::OK); // set HTTP response code
$this->response->setBodyJSON($ this->request->getData()); // set responde data
return $this->response; // return response object
}
namespace apisecure;
use DiomacAPIException;
use DiomacAPIForbiddenException;
use DiomacAPIUnauthorizedException;
use DiomacAPIResponse;
use DiomacAPIGuard;
/**
* Class AuthGuard
* @package apisecure
*/
class AuthGuard implements Guard
{
/**
* @param object|null $guardParams
* @return bool
* @throws Exception
* @throws ForbiddenException
* @throws UnauthorizedException
*/
public function guard(object $guardParams = null) : bool
{
$func = $guardParams->func;
$access = checkAccess($func);
switch ($access) {
case Response::OK:
return true;
break;
case Response::UNAUTHORIZED:
throw new UnauthorizedException();
break;
case Response::FORBIDDEN:
throw new ForbiddenException();
break;
default:
throw new Exception('Server Error!', Response::INTERNAL_SERVER_ERROR);
}
}
}
キャッシュ設定では、マッピングされたルートがリストに保存され、使用すると (true に設定すると)、ルート マッピングの手順がスキップされ、パフォーマンスが向上します。
**
* Setting use cache for caching of annotations mapping
*/
$config->setUseCache(true);
/**
* Execute API
*/
try{
$app = new App($config);
$app->exec();
}catch (Exception $ex){
...
}
/**
* Set Redis for cache
*/
$redis = new RedisConfig();
$redis->setScheme('tcp');
$redis->setHost('redis');
$redis->setPort(6379);
**
* Setting use cache for caching of annotations mapping
*/
$config->setUseCache(true, $redis);
以下の例のようなルートをリソース内に作成します。
PHP クラス:
use DiomacAPIResource;
use DiomacAPIResponse;
use examplev1docExampleSwaggerDoc;
class ExampleSwaggerJson extends Resource
{
/**
* @method get
* @route /swagger.json
*/
function swaggerJson()
{
$this->response->setCode(Response::OK);
$swagger = new ExampleSwaggerDoc();
/**
* JSON
*/
$this->response->setBodySwaggerJSON($swagger);
/**
* Or YAML
*/
//$this->response->setBodySwaggerYAML($swagger);
return $this->response;
}
}
ルート結果:
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Sample App",
"description": "This is a sample server Petstore server.",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"email": "[email protected]",
"url": "http://swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"host": "localhost",
"basePath": "/php-api-rest/vendor/example/v1",
"schemes": [
"http",
"https"
],
"consumes": [
"text/plain; charset=utf-8"
],
"produces": [
"application/json",
"text/html"
],
"tags": [
{
"name": "ExampleAPIDocSwagger",
"description": "ExampleAPIDocSwagger",
"externalDocs": {
"description": "Externaldocsexample",
"url": "http://example_php_api_rest.com"
}
}
],
"paths": {
...
API の情報 (Swagger Info) を文書化するには、Swagger クラスと SwaggerInfo クラスを使用できます。以下の例のように、Swagger を継承する「ExampleSwaggerDoc」クラスを実装するだけです。
PHP クラス:
use DiomacAPIswaggerSwagger;
use DiomacAPIswaggerSwaggerInfo;
class ExampleSwaggerDoc extends Swagger
{
public function info(): SwaggerInfo
{
$this->setInfo(new SwaggerInfo());
$this->info->setVersion('1.0.0');
$this->info->setTitle('Swagger Sample App');
$this->info->setDescription('This is a sample server Petstore server.');
$this->info->setTermsOfService('http://swagger.io/terms/');
$this->info->getContact()->setName('API Support');
$this->info->getContact()->setEmail('[email protected]');
$this->info->getContact()->setUrl('http://swagger.io');
$this->info->getLicense()->setName('Apache 2.0');
$this->info->getLicense()->setUrl('http://www.apache.org/licenses/LICENSE-2.0.html');
return $this->getInfo();
}
...
}
PHPDoc:
/**
* Class ExampleResource
* @package examplev1
* @tag(
* name="Example API Doc Swagger",
* description="Example API Doc Swagger",
* @externalDocs(description="External docs example", url="http://example_php_api_rest.com")
* )
*/
class ExampleResource extends Resource
{
...
}
Swagger json の結果:
...
"tags": [
{
"name": "ExampleAPIDocSwagger",
"description": "ExampleAPIDocSwagger",
"externalDocs": {
"description": "Externaldocsexample",
"url": "http://example_php_api_rest.com"
}
}
],
...
PHPDoc:
/**
* @method get
* @route /example/api/value1/{value1}/value2/{value2}
* @tag More one tag
*/
function getUsrData(): Response
{
...
}
Swagger json の結果:
...
"tags": [
"More one tag",
"ExampleAPIDocSwagger"
],
...
PHPDoc:
/**
* @method get
* @route /example/api/value1/{value1}/value2/{value2}
* @contentType application/json
* @contentType text/html
*/
function getUsrData(): Response
{
...
}
Swagger json の結果:
...
"produces": [
"application/json",
"text/html"
],
...
PHPDoc:
/**
* @method get
* @route /example/api/value1/{value1}/value2/{value2}
* @summary Example api rest php
*/
function getUsrData(): Response
{
...
}
Swagger json の結果:
...
"get": {
"summary": "Example api rest php",
...
PHPDoc:
/**
* @method get
* @route /example/api/value1/{value1}/value2/{value2}
* @description A example api rest php
*/
function getUsrData(): Response
{
...
}
Swagger json の結果:
...
"get": {
"description": "A example api rest php",
...
PHPDoc:
/**
* @method get
* @route /example/api/value1/{value1}/value2/{value2}
* @operationId GETUSERDATA
*/
function getUsrData(): Response
{
...
}
Swagger json の結果:
...
"get": {
"operationId": "GETUSERDATA",
...
PHPDoc:
/**
* @method get
* @route /example/api/value1/{value1}/value2/{value2}
* @consumeType text/plain; charset=utf-8
*/
function getUsrData(): Response
{
...
}
Swagger json の結果:
...
"post": {
"consumes": [
"text/plain; charset=utf-8"
],
...
PHPDoc:
/**
* @method get
* @route /example/api/value1/{value1}/value2/{value2}
* @response(
* code=200,
* description="Success",
* @schema(
* type="object",
* @items($ref="#/definitions/sucess")
* )
* )
*/
function getUsrData(): Response
{
...
}
Swagger json の結果:
...
"responses": {
"200": {
"description": "Success",
"schema": {
"type": "object",
"items": {
"$ref": "#/definitions/sucess"
}
}
},
...
このプロジェクトは MIT ライセンスに基づいてライセンスされています - 詳細については LICENSE ファイルを参照してください