json-rest
Json response builder library for php., (*1)
Installation
Composer
Add to your composer.json or create a new composer.json:, (*2)
{
"require": {
"tansandbox/json-rest": "*"
}
}
Tell the composer to download the library by running the command:, (*3)
$ php composer.phar install
To include using compser require, run the following command from your project., (*4)
$ php composer.phar require tansandbox/json-rest
Basic usages
Creating object
use TanSandbox\JsonRest\Builder;
$builder = new Builder() ;
Returning a success response
$data = array (
'name' => 'Nithin',
'subject' => 'English',
'mark' => '90'
);
$builder->ok()->send($data) ;
Will produce, (*5)
{
"status": true,
"data": {
"name": "Nithin",
"subject": "English",
"mark": "90"
}
}
Return a failure
$data = array(
'name' => 'Please provide a valid name'
);
$builder->fail()->send($data) ;
Will produce, (*6)
{
"status": false,
"data": {
"name": "Please provide a valid name"
}
}
Response with custom http status
$data = array(
'reply' => 'Resource not found.'
);
$builder->setStatus(404)->send($data) ;
Will produce, (*7)
{
"status": false,
"data": {
"reply": "Resource not found."
}
}
Advanced response
$data = array (
'name' => 'Nithin',
'subject' => 'English',
'mark' => '90'
);
$builder->setMessage('Action completed')->setStatus(200)->send($data) ;
Will produce, (*8)
{
"status": false,
"data": {
"name": "Nithin",
"subject": "English",
"mark": "90"
},
"message": "Action completed"
}
Method chaining.
New json member can be added using the setXXX methods. The sendie() method is to output the reponse and to die after that., (*9)
$builder->setName('Nithin')
->setSubject('English')
->setMark('90')
->setCustomNotes('Student of ZF2')
->sendie() ;
Will produce, (*10)
{
"status": true,
"message": "Action completed",
"name": "Nithin",
"subject": "English",
"mark": "90",
"customNotes": "Student of ZF2"
}