Created
December 19, 2012 20:17
-
-
Save jasdeepkhalsa/4340088 to your computer and use it in GitHub Desktop.
Simple PHP REST / JSON Server with example.php by Jake Sankey (http://jakesankey.com/blog/2012/09/php-simple-rest-server/)
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 | |
// example request: http://path/to/resource/Example?method=sayHello&name=World | |
require_once "RestServer.php"; | |
$rest = new RestServer(Hello); | |
$rest->handle(); | |
class Hello | |
{ | |
public static function sayHello($name) | |
{ | |
return "Hello, " . $name; | |
} | |
} | |
?> |
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 | |
class RestServer | |
{ | |
public $serviceClass; | |
public function __construct($serviceClass) | |
{ | |
$this->serviceClass = $serviceClass; | |
} | |
public function handle() | |
{ | |
if (array_key_exists("method", array_change_key_case($_REQUEST, CASE_LOWER))) | |
{ | |
$rArray = array_change_key_case($_REQUEST, CASE_LOWER); | |
$method = $rArray["method"]; | |
if (method_exists($this->serviceClass, $method)) | |
{ | |
$ref = new ReflectionMethod($this->serviceClass, $method); | |
$params = $ref->getParameters(); | |
$pCount = count($params); | |
$pArray = array(); | |
$paramStr = ""; | |
$i = 0; | |
foreach ($params as $param) | |
{ | |
$pArray[strtolower($param->getName())] = null; | |
$paramStr .= $param->getName(); | |
if ($i != $pCount-1) | |
{ | |
$paramStr .= ", "; | |
} | |
$i++; | |
} | |
foreach ($pArray as $key => $val) | |
{ | |
$pArray[strtolower($key)] = $rArray[strtolower($key)]; | |
} | |
if (count($pArray) == $pCount && !in_array(null, $pArray)) | |
{ | |
echo call_user_func_array(array($this->serviceClass, $method), $pArray); | |
} | |
else | |
{ | |
echo json_encode(array('error' => "Required parameter(s) for ". $method .": ". $paramStr)); | |
} | |
} | |
else | |
{ | |
echo json_encode(array('error' => "The method " . $method . " does not exist.")); | |
} | |
} | |
else | |
{ | |
echo json_encode(array('error' => 'No method was requested.')); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment