PHP implementation of the JSend specification
PHP Shell
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.

README.md

Build Status
Test Coverage
Code Climate
Issue Count

Total Downloads

JSend

A simple PHP implementation of the JSend specification.

Usage

use JSend\JSendResponse;

New response

$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.

Convert JSendResponse to JSON

__toString() is overridden to encode JSON automatically.

$json = $success->encode();
$json = (string) $success;

As JSendResponse is JsonSerializable, you can use the object directly in json_encode

json_encode($success);

Setting flags

You can set flags if needed:

$success->setEncodingOptions(\JSON_PRETTY_PRINT | \JSON_BIGINT_AS_STRING);
$json = $success->encode();

Convert JSON to JSendResponse

try {
    $response = JSendResponse::decode($json);
} catch (InvalidJSendException $e) {
    echo "You done gone passed me invalid JSend.";
}

Send JSON as HTTP Response

This sets the Content-Type header to application/json and spits out the JSON.

$jsend = new JSendResponse('success', $data);
$jsend->respond();

Get info

$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;
}

Credits

The library was written by Jamie Schembri. It has been transfered to the current account Nanne Huiges in december 2015.