Skip to content
forked from NanneHuiges/JSend

PHP implementation of the JSend specification. Comes with Laravel service provider.

License

Notifications You must be signed in to change notification settings

quanganhdo/JSend

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

PHP implementation of the JSend specification. Comes with Laravel service provider.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%