Writing a JSON View Class for the Slim PHP Framework

3 August 2015| Post by Graham

AuthorGraham

Here is a quick JSON view class I recently wrote when building a REST API for a client. It allows you to quickly return a JSON response with a HTTP status code.

				

namespace MyAppView;

class JSONView extends SlimView {

/**
* Sets response body of appended data to be json_encoded
*
* @param int $status
* @param array|null $data
* @return void
*/
public function render($status = 200, $data = array()) {

$data = array_merge(array(‘status’ => $status), $this->all(), is_array($data) ? $data : array());

if (isset($data[‘flash’]) && is_object($data[‘flash’])) {
$flash = $this->data->flash->getMessages();
if (count($flash)) {
$data[‘flash’] = $flash;
} else {
unset($data[‘flash’]);
}
}

$app = SlimSlim::getInstance();

$response = $app->response();

$response->status($status);
$response->header(‘Content-Type’, ‘application/json’);
$response->body(json_encode($data));

$app->stop();
}

}

Usage

If you are just wanting to use this on an individual routes and not application wide, you can use it as :

				

$app = new SlimSlim;

$app->get(‘/test’, function() use($app){

$app->view(new MyAppJSONView);

$app->render(200,array(
‘error’ => false,
‘msg’ => ‘successful response’,
‘data’ => array(
‘products’ => array()
)
));
});

If you would like to use it application wide, then simply assign it before any routes are called as below :

				

$app = new SlimSlim;

$app->view(new MyAppJSONView);

$app->get(‘/test’, function() use($app){
$app->render(200,array(
‘error’ => false,
‘msg’ => ‘successful response’,
‘data’ => array(
‘products’ => array()
)
));
});

Scroll