I am trying to create JSON-RPC HTTP service. I am using POST method.
rest.php
<?php
header('Content-Type: application/json');
$input = file_get_contents("php://input");
$json = json_decode($input);
$output = $json->num + 10;
echo json_encode($output);
?>
Input:
{"num": 10 }
Output:
20
Now I am trying to implement more methods, so then I can use input like this:
{
"method":"add",
"params": {
"num1": 15,
"num2": 10
}
}
So I add function to rest.php:
public function add($n1, $n2) {
return $n1 + $n2;
}
Q: How to determine called method and execute it in rest.php with new input?
EDIT:
<?php
header('Content-Type: application/json');
$input = file_get_contents("php://input");
$json = json_decode($input);
foreach ($json->params as $param) {
$params[] = $param;
}
$output = call_user_func_array($json->method, $params);
echo json_encode($output);
function add($n1, $n2) {
return $n1 + $n2;
}