Last active
August 29, 2015 14:04
-
-
Save tsuriga/004fe7c585435c6a9673 to your computer and use it in GitHub Desktop.
A simple API with PHP
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
RewriteEngine On | |
RewriteCond %{REQUEST_FILENAME} !-f | |
RewriteRule ^ index.php [QSA,L] |
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 | |
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); | |
} | |
} |
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 | |
// 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