Skip to content

Instantly share code, notes, and snippets.

@moopet
Created February 16, 2015 14:07
Show Gist options
  • Save moopet/cb9669b32a5c3019d41b to your computer and use it in GitHub Desktop.
Save moopet/cb9669b32a5c3019d41b to your computer and use it in GitHub Desktop.
REST services for industrious 1980s executives on a budget.
<?php
class BudgetRest {
/**
*
*/
public function __construct() {
if (!empty($_SERVER['PATH_INFO'])) {
$sections = explode('/', trim($_SERVER['PATH_INFO'], '/'));
} elseif (!empty($_SERVER['REQUEST_URI']) && !empty($_SERVER['PHP_SELF'])) {
$sections = str_replace($_SERVER['PHP_SELF'], '', $_SERVER['REQUEST_URI']);
$sections = str_replace('//', '/', $sections);
$sections = trim($sections, '?');
$sections = explode('/', trim($sections, '/'));
} else {
$this->error(404);
}
$this->base_url = "//{$_SERVER['HTTP_HOST']}" . dirname($_SERVER['PHP_SELF']);
$method = strtolower(array_shift($sections));
$explicit_method = $method . '_' . strtolower($_SERVER['REQUEST_METHOD']);
if (method_exists($this, $explicit_method)) {
$method = $explicit_method;
}
if (strpos($method, '_') !== 0 && method_exists($this, $method)) {
try {
$data = call_user_func_array(array($this, $method), $sections);
$this->_json($data);
} catch(\Exception $e) {
$this->_error(500);
}
} else {
$this->_error(404);
}
}
/**
*
*/
protected function _error($code=500) {
switch($code) {
case 404:
header("HTTP/1.0 404 Not Found");
break;
case 500:
default:
header("HTTP/1.0 Internal Server Error");
break;
}
exit(1);
}
/**
*
*/
protected function _json($data) {
$this->_sent_data = TRUE;
header('Content-Type: application/json');
if (is_array($data)) {
$data = $this->_sanitize_json($data);
echo json_encode($data);
} else {
echo "null";
}
exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment