razonyang / yii2-jsend
JSend port for Yii2
Installs: 4 187
Dependents: 1
Suggesters: 0
Security: 0
Stars: 5
Watchers: 3
Forks: 0
Open Issues: 0
Type:yii2-extension
Requires
- razonyang/jsend: ^1.0
- yiisoft/yii2: ~2.0.13
Requires (Dev)
- phpunit/phpunit: ^7
This package is auto-updated.
Last update: 2024-12-13 10:03:46 UTC
README
The package is a Yii2's implementation of JSend specification.
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" }