A simple PHP implementation of the JSend specification.
Add "quanganhdo/jsend": "dev-master" to composer.json's require list.
Add the followings to the repositories list in the same file:
{
"type": "vcs",
"url": "git@github.com:quanganhdo/JSend.git"
}
use JSend\JSendResponse;$success = new JSendResponse('success', $data);
$fail = new JSendResponse('fail', $data);
$error = new JSendResponse('error', $data, 'Not cool.', 9001);$success = JSendResponse::success($data);
$fail = JSendResponse::fail($data);
$error = JSendResponse::error('Not cool.', 9001, $data);Note: an InvalidJSendException is thrown if the status is invalid or if you're creating an error without a message.
__toString() is overridden to encode JSON automatically.
$json = $success->encode();
$json = (string) $success;try {
$response = JSendResponse::decode($json);
} catch (InvalidJSendException $e) {
echo "You done gone passed me invalid JSend.";
}This sets the Content-Type header to application/json and spits out the JSON.
$jsend = new JSendResponse('success', $data);
$jsend->respond();$isSuccess = $response->isSuccess();
$isError = $response->isError();
$isFail = $response->isFail();
$status = $response->getStatus();
$data = $response->getData();
$array = $response->asArray();Additionally, you can call the following methods on an error. A BadMethodCallException is thrown if the status is not error, so check first.
if ($response->isError()) {
$code = $response->getErrorCode;
$message = $response->getErrorMessage;
}Add JSend\Laravel\JSendServiceProvider to the providers array in app/config/app.php.
Add JSendResponse to the aliases array in the same file.