https://github.com/razonyang/yii2-jsend
JSend formatter, serializer and error handler for Yii2
https://github.com/razonyang/yii2-jsend
yii2-jsend
Last synced: about 2 months ago
JSON representation
JSend formatter, serializer and error handler for Yii2
- Host: GitHub
- URL: https://github.com/razonyang/yii2-jsend
- Owner: razonyang
- License: bsd-3-clause
- Created: 2019-08-05T07:33:58.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2019-08-21T08:13:30.000Z (almost 6 years ago)
- Last Synced: 2025-05-12T19:10:00.753Z (about 2 months ago)
- Topics: yii2-jsend
- Language: PHP
- Size: 6.84 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
JSend port for Yii2
===================[](https://travis-ci.org/razonyang/yii2-jsend)
[](https://scrutinizer-ci.com/g/razonyang/yii2-jsend/?branch=master)
[](https://scrutinizer-ci.com/g/razonyang/yii2-jsend/?branch=master)
[](https://packagist.org/packages/razonyang/yii2-jsend)
[](https://packagist.org/packages/razonyang/yii2-jsend)
[](LICENSE)The package is a Yii2's implementation of [JSend](https://github.com/omniti-labs/jsend) specification.
Installation
------------```
composer require razonyang/yii2-jsend
```Usage
-----Update resposne formater and error handler:
```php
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:
```php
public $serializer = \RazonYang\Yii2\JSend\Serializer::class;
```Error Handler
-------------`ErrorHandler` converts exception to error payload:
```json
{
"status": "error",
"code": "exception code",
"message": "exception message"
}
```It can also returns the optional data field by throwing a JSend's Exception:
```php
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();
``````json
{
"status": "error",
"code": "exception code",
"message": "exception message",
"data": "exception data"
}
```