PHP implementation of a simple JSON RPC framework instance _php tips

Source: Internet
Author: User

JSON RPC, a remote invocation service with JSON as a message format, is a set of specifications and a series of implementations that allow programs that run on different operating systems, different environments, to implement internet-based process calls. This remote procedure call can use HTTP as a transport protocol, or it can use other transport protocols, and the content of the transfer is the JSON message body.

Here we code a set of PHP-based RPC frameworks that contain RPC server servers and application-side client;

(a) PHP service end Rpcserver jsonrpcserver.php

Copy Code code as follows:

Class Jsonrpcserver {
/**
* Process a request class that has a number of parameter bindings in it
* @param object $object
* @return Boolean
*/
public static function handle ($object) {
To determine if it is an RPC JSON request
if ($_server[' Request_method ']!= ' POST ' | | empty ($_server[' content_type '])
|| $_server[' Content_Type ']!= ' Application/json ') {
return false;
}
Reads the input data
$request = Json_decode (file_get_contents (' Php://input '), true);
Executing interfaces in the request class
try {
if ($result = @call_user_func_array (Array ($object, $request [' method ']), $request [' params ']) {
$response = array (' ID ' => $request [' id '], ' result ' => $result, ' error ' => NULL);
} else {
$response = array (' ID ' => $request [' id '], ' result ' => NULL,
' Error ' => ' unknown method or incorrect parameters ');}
catch (Exception $e) {
$response = array (' ID ' => $request [' id '], ' result ' => NULL, ' error ' => $e->getmessage ());
}
JSON format output
if (!empty ($request [' ID '])) {//notifications don ' t want response
Header (' Content-type:text/javascript ');
echo Json_encode ($response);
}
return true;
}
}

Two RPC Client, jsonrpcclient.php

Copy Code code as follows:

<?php
/*
*/
Class Jsonrpcclient {

Private $debug;
Private $url;
Request ID
Private $id;
Private $notification = false;
/**
* @param $url
* @param bool $debug
*/
Public function __construct ($url, $debug = False) {
Server URL
$this->url = $url;
Proxy
Empty ($proxy)? $this->proxy = ': $this->proxy = $proxy;
Debug state
Empty ($debug)? $this->debug = false: $this->debug = true;
Message ID
$this->id = 1;
}

/**
*
* @param boolean $notification
*/
Public Function Setrpcnotification ($notification) {
Empty ($notification)? $this->notification = false: $this->notification = true;
}

/**
* @param $method
* @param $params
* @return BOOL
* @throws Exception
*/
Public Function __call ($method, $params) {
Inspection request Information
if (!is_scalar ($method)) {
throw new Exception (' method name has no scalar value ');
}
if (Is_array ($params)) {
$params = Array_values ($params);
} else {
throw new Exception (' Params must be given as array ');
}

if ($this->notification) {
$currentId = NULL;
} else {
$currentId = $this->id;
}

Assemble into a request
$request = Array (' method ' => $method, ' params ' => $params, ' id ' => $currentId);
$request = Json_encode ($request);
$this->debug && $this->debug.= ' * * * * * * * * *. \ n ". $request." \ n '. ' End of Request * * *. \ n ';
$opts = Array (' http ' => array (
' Method ' => ' POST ',
' Header ' => ' Content-type:application/json ',
' Content ' => $request
));
Key several
$context = Stream_context_create ($opts);
if ($result = file_get_contents ($this->url, False, $context)) {
$response = Json_decode ($result, true);
} else {
throw new Exception (' Unable to connect to '. $this->url);
}
Output Debugging information
if ($this->debug) {
Echo nl2br (($this->debug));
}
Inspection response Information
if (! $this->notification) {
Check
if ($response [' id ']!= $currentId) {
throw new Exception (' Incorrect response ID (Request ID: '. $currentId. ', Response ID: '. $response [' id ']. ');
}
if (!is_null ($response [' Error '])) {
throw new Exception (' Request error: '. $response [' ERROR ']];
}
return $response [' result '];

} else {
return true;
}
}
}
?>

(iii) Application examples
(1) Service End server.php

Copy Code code as follows:

<?php
Require_once ' jsonrpcserver.php ';

Copy Code code as follows:

Member as test class
Require ' member.php ';
Service-side invocation
$myExample = new Member ();
Injecting an instance
Jsonrpcserver::handle ($myExample)
or print ' no request ';
?>

(2) Test class file, member.php

Copy Code code as follows:

Class member{
Public Function GetName () {
Return ' Hello word '; return string
}
}

(3) Client client.php

Copy Code code as follows:

Require_once ' jsonrpcclient.php ';

$url = ' http://localhost/rpc/server.php ';
$myExample = new Jsonrpcclient ($url);

Client Calls
try {
$name = $myExample->getname ();
Echo $name;
catch (Exception $e) {
Echo nl2br ($e->getmessage ()). ' <br/> '. ' \ n ";
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.