rgen3/yii2-json-api-controller

Yii2 简单的基于 json 的控制器。

0.0.2 2018-05-24 06:45 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:32:07 UTC


README

提供使用原生 Yii2 模型规则进行友好请求验证处理 json 请求的可能性

安装

composer require rgen3/yii2-json-api-controller

注意

您可以使用此控制器与简单的 json 客户端 https://github.com/rgen3/restapi-core-client

使用示例

创建一个请求文件夹和一个请求类

<?php

namespace app\requests;

use yii\base\Model;

class MyRequest extends Model 
{
    public $exampleVar;

    public function rules()
    {
        return [
            ['exampleVar', 'required'],
        ];
    }
}

创建一个控制器

<?php

use rgen3\controller\json\BaseController;
use app\requests\MyRequest;


class SiteController extends BaseController
{
    // Note sending data to autoload for the request you should use key named `data` as wrapper
    // for you json request
    //
    // i.e. here as input datum you have to use
    // "
    //  {"data" : {"exampleVar" : "myValue" }}
    // "
    public function actionIndex(MyRequest $request)
    {
        // return any success response
        return $this->success([
            'theValue' => $request->exampleVar,
        ]);
    }

    // Also you can any typehints to provide a native yii2 behaviour
    public function actionError(int $anyVar = 0)
    {
        // $anyVar will contains your value or zero
        return $this->error(['Error data']);
    }

    // Also you can leave input params empty
    public function actionThrows()
    {
        // Throw any exception you want
        throw new yii\web\BadRequestHttpException('The exception');
    }
    
    public function actionAnotherException()
    {
        throw new \Exception('Not http exception');
    }
}

当您调用 actionIndex 时,您将获得

    {
      "request-id": null,
      "status-code": 200,
      "status-text": "OK",
      "status": "success",
      "data": {
        "theValue": "your value"
      }
    }

注意:您应该生成请求ID并将其设置为 X-Request-Id HTTP头

调用 actionError 时,您将获得

{
  "request-id": null,
  "status-code": 200,
  "status-text": "OK",
  "status": "error",
  "data": [
    "Error class"
  ]
}

执行 actionThrows 返回

{
  "request-id": null,
  "status-code": 400,
  "status-text": "Bad Request",
  "status": "error",
  "data": [
    
  ]
}

如果您有未处理的异常,如 actionAnotherException,您将获得

{
  "request-id": null,
  "status-code": 500,
  "status-text": "Internal Server Error",
  "status": "error",
  "data": [
    "Not http exception"
  ]
}