I have created an api in php and I was hoping some clever individuals would mind reviewing it to see what I could do better. I have commented it heavily to explain my reasoning. please feel free to pick holes wherever you can!
//On my page 'localhost/api'
if (!$_POST) {
die('No direct access allowed');
}
include('/api/gateway.php'); //Pull in my Gateway class
try {
$api = new Gateway($_POST);
}
catch (Exception $e) {
//Catch any exceptions thrown in the api and return them as a bad request
echo json_encode( array(
'status'=> 400,
'params'=> $_POST,
'data'=> array(
'message'=> $e->getMessage(),
'file'=> $e->getFile(),
'line'=> $e->getLine()
)
));
}
My Gateway class then deals with the api call.
class Gateway {
function __construct($params) {
$this->params = (isset($params) ? $params : array());
if ( !isset($params['method']) ) {
throw new Exception('No method passed to API');
}
$method = explode('.', $params['method']);
if ( !class_exists($method[0]) ) {
throw new Exception('No class by the name of ' . $method[0]);
}
if ( !method_exists($method[0], $method[1]) ) {
throw new Exception('No method in ' . $method[0] . ' called ' . $method[1]);
}
//Call my class and method without instantiating it.
$result = $method[0]::$method[1]($params);
if (!$result) {
//This shouldn't really fire as it should be handled in the method.
$this->error();
}
else {
$this->send(200, $result, $params);
}
}
public $params; //$_POST parameters stored here to return if an error is thrown
public function error($code = 400, $data = array(), $params = array()) {
echo json_encode( array(
'status'=> 400,
'params'=> $this->$params,
'data'=> $data
));
}
public function send($code = 200, $data = array(), $params = array()) {
echo json_encode( array(
'status'=> 200,
'params'=> $this->params,
'data'=> $data
));
}
}
Example of my api classes. These are currently in the same file as my Gateway class. Eventually these will be moved into a separate folder and pulled in dynamically.
class Sites {
public function getSites($params) {
return array(
'gotyou'=> 'message'
);
}
}