the-real-start/yii2-jsend-response

一组小工具,帮助处理 JSend 规范(见 https://labs.omniti.com/labs/jsend)。该软件包是为 yii2 框架和 yii2-oauth2-server 设计的。该软件包旨在简化使用这些工具构建 API 响应的过程。

v0.1.4 2016-08-24 06:28 UTC

This package is not auto-updated.

Last update: 2024-09-26 03:06:24 UTC


README

服务器以 JSend 格式生成响应(见 https://labs.omniti.com/labs/jsend)。软件包包含以下类

TRS\RestResponse\interfaces

TemplateInterface

TRS\RestResponse\templates

BaseTemplate

TRS\RestResponse\jsend

Response

示例

// your template class
// templates needs for formating data section in response (remove some data for example)
use TRS\RestResponse\templates\BaseTemplate
class ProductSmallTemplate extends BaseTemplate
{
    protected function prepareResult()
        {
            $this->result = [
                'id'          => $this->model->id,
                'title'       => $this->model->title,
                'description' => $this->model->description,
                // exclude other fields (prices, discounts etc.)
            ];
        }
}

// model
class Product extends BaseProduct
{
    // you can use any other method name
    public function getAsArray($template = 'small')
        {
            if ($template == 'small') {
                $template = new ProductSmallTemplate($this);
            } else {
                throw new \InvalidArgumentException('Invalid template "' . $template . '"');
            }
            return [ 'Product' => $template->getAsArray() ];
        }
}

// controller
use TRS\RestResponse\jsend\Response
class ProductsController extends BaseController
{
    public function actionShow($id)
    {
        $product = Product::find()->localized()->andWhere(['id' => $id])->one();
        Response::success($product->getAsArray('small'))->send();
    }
}

安装

要通过 composer 安装此包,需要在您的 composer.json 中指定额外的源(因为该包不在公开访问中),并指定该包。

...
"require": {
...
	"the-real-start/yii2-jsend-response": "*"
}
...

或者通过控制台安装

composer require the-real-start/yii2-jsend-response

安装后,所有扩展类都可通过 namespace TRS\RestResponse 访问。

文档

代码尽可能进行了良好的文档编制,并允许生成可读的 phpdoc

简要说明如何生成文档。

生成 phpdoc

用于根据代码生成文档的命令

phpdoc run -d ./ -t doc/ -i vendor/