Skip to content
PHP implementation of the JSend specification. Comes with Laravel service provider.
PHP
Branch: master
Clone or download
Pull request Compare This branch is 4 commits ahead, 69 commits behind NanneHuiges:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src/JSend
tests
.gitignore
LICENSE
README.md
composer.json
phpunit.xml

README.md

JSend

A simple PHP implementation of the JSend specification.

Installation

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"
}

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;

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

Laravel Service Provider

Add JSend\Laravel\JSendServiceProvider to the providers array in app/config/app.php.

Add JSendResponse to the aliases array in the same file.

You can’t perform that action at this time.