Skip to content

Instantly share code, notes, and snippets.

@tsuriga
Last active August 29, 2015 14:04
Show Gist options
  • Save tsuriga/004fe7c585435c6a9673 to your computer and use it in GitHub Desktop.
Save tsuriga/004fe7c585435c6a9673 to your computer and use it in GitHub Desktop.
A simple API with PHP
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
<?php
namespace tsu\http;
trait ApiTrait
{
public function route()
{
$httpMethod = strtolower(@$_SERVER['REQUEST_METHOD']);
$action = ucfirst(
explode(
'/',
str_replace(
dirname(@$_SERVER['SCRIPT_NAME']) . '/',
'',
@$_SERVER['REDIRECT_URL']
),
2
)[0]
);
$method = $httpMethod . $action;
if (method_exists($this, $method)) {
$parameters = [];
if ($httpMethod === 'get') {
$parameters = $_GET;
} else {
parse_str(file_get_contents('php://input'), $parameters);
}
$this->$method($parameters);
} else {
$route = strtoupper($httpMethod) . '/' . lcfirst($action);
throw new BadMethodCallException(
'Route ' . $route . ' not supported'
);
}
}
public function respond($code, array $data)
{
header('Content-Type: application/json', false, $code);
echo json_encode($data);
}
}
<?php
// Usage example
// Set up autoloading e.g. using https://gist.github.com/jwage/221634
use tsu\http\ApiTrait;
class App
{
use ApiTrait;
public function run()
{
$this->route();
}
protected function getTest(array $data)
{
$this->respond(200, $data);
}
}
(new App())->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment