Last active
November 11, 2015 14:48
-
-
Save connordavison/409a0b0597e2074d3885 to your computer and use it in GitHub Desktop.
A JSend compliant JSONResponse class. https://labs.omniti.com/labs/jsend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class JSONResponse implements JSend, Sendable | |
{ | |
private $data; | |
public function error($message, $code = 0, $data = null) | |
{ | |
$this->data = array( | |
'status' => self::STATUS_ERROR, | |
'data' => $data, | |
'message' => $message | |
); | |
if ($code > 0) { | |
$this->data['code'] = (int) $code; | |
} | |
} | |
public function fail($data) | |
{ | |
$this->data = array( | |
'status' => self::STATUS_FAIL, | |
'data' => $data | |
); | |
} | |
public function success($data = null) | |
{ | |
$this->data = array( | |
'status' => self::STATUS_SUCCESS, | |
'data' => $data | |
); | |
} | |
public function send() | |
{ | |
if (isset($this->data)) { | |
header('Content-Type: application/json'); | |
die(json_encode($this->data)); | |
} else { | |
throw new \LogicException("Cannot send an empty response."); | |
} | |
} | |
} | |
interface JSend | |
{ | |
const STATUS_SUCCESS = 'success'; | |
const STATUS_FAIL = 'fail'; | |
const STATUS_ERROR = 'error'; | |
public function error($message, $code = 0, $data = null); | |
public function fail($data); | |
public function success($message); | |
} | |
interface Sendable | |
{ | |
public function send(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment