0

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;
}

1 Answer 1

1

You can use method_exists and function_exists (depending of your needs) to check if the string you get matches an existing element.

Then, you can use call_user_func or call_user_method to execute the function.

For example :

<?php
class foo{
    public function add($n1, $n2) {
        return $n1 + $n2;
    } 
}

$method = "add";
$object = new foo();
$n1 = 1;
$n2 = 8;
if(method_exists($object, $method))
{
    call_user_method($method, $object, $n1, $n2);
}

EDIT : In this example, I assigned n1 and n2 parameters hard coded values. In your case, you can get the params array you get from the JSON and give it as parameter to all your methods. In this way, you don't have to test received parameters outside the method body.

Sign up to request clarification or add additional context in comments.

1 Comment

added my test to original post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.