Yii2 JSend

Yii2 JSend

Build Status
Scrutinizer Code Quality
Code Coverage
Latest Stable Version
Total Downloads
LICENSE

The package is an implementation of JSend specification for Yii2, provides JSend formatter, serializer and error handler.

Installation

composer require razonyang/yii2-jsend

Usage

Update resposne formater and error handler:

return [
    'components' => [
        'response' => [
            'formatters' => [
                \yii\web\Response::JSON => [
                    'class' => \RazonYang\Yii2\JSend\Formatter::class,
                ],
            ],
        ],
        'errorHandler' => [
            'class' => \RazonYang\Yii2\JSend\ErrorHandler::class,
        ],
    ],
];

Change you rest controller serializer:

public $serializer = \RazonYang\Yii2\JSend\Serializer::class;

Error Handler

ErrorHandler converts exception to error payload:

{
    "status": "error",
    "code": "exception code",
    "message": "exception message"
}

It can also returns the optional data field by throwing a JSend's Exception:

throws new RazonYang\Jsend\Exception($message, $code, $data, $previous);

// you can also define your own exception:
class MyException extends RazonYang\Jsend\Exception
{
}

throws new MyException();
{
    "status": "error",
    "code": "exception code",
    "message": "exception message",
    "data": "exception data"
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据