Skip to content

Instantly share code, notes, and snippets.

@joseph-montanez
Created March 4, 2012 01:37
Show Gist options
  • Save joseph-montanez/1969799 to your computer and use it in GitHub Desktop.
Save joseph-montanez/1969799 to your computer and use it in GitHub Desktop.
JSON-RPC server in PHP

== JSON-RPC ==

This is designed to have to autoload calls and return a json object. It supports PHP 5.3's namespaces, and relies on PHP's built in Reflection.

Example: htttp://localhost/rpc.php?0={"method":"foo\myclass::hello","params":[], "id":2}

Returns: {"result":"Hello World","error":null,"id":2}

Based off: filename: "foo/myclass.php" source: {{{

}}}

<?php
function __autoload($class_name) {
include $class_name . '.php';
}
//-- Run the front controller
$obj = json_decode(current($_REQUEST));
if ($obj) {
$params = (array) $obj->params;
$method = $obj->method;
$parts = explode('::', $method);
$class_name = $parts[0];
$method_name = $parts[1];
if (file_exists($class_name . '.php')) {
$ref = new ReflectionClass($class_name);
if ($ref->hasMethod($method_name)) {
$fn = $ref->getMethod($method_name);
//-- Make sure this function is registered as an endpoint
$is_endpoint = stristr($fn->getDocComment(), '@endpoint') !== false;
if ($is_endpoint) {
$result = $fn->invokeArgs(null, $params);
} else {
$result = null;
$error = 'Method "' . $method_name . '" is not a registered endpoint.';
}
} else {
$result = null;
$error = 'Method "' . $method_name . '" not found';
}
} else {
$result = null;
$error = 'Class "' . $class_name . '" not found';
}
echo json_encode(array(
'result' => $result,
'error' => $error,
'id' => (int) $obj->id
));
} else {
echo json_encode(array(
'result' => null,
'error' => 'Unable parse JSON correctly',
'id' => (int) $obj->id
));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment