-
Notifications
You must be signed in to change notification settings - Fork 29
Advanced functionality
The library is designed to be flexible. It allows you to substitute the built-in transport mechanism for sending and receiving requests with one of your own. The following transports are used by default:
- the client calls
file_get_contents
using a stream-context - the server reads
php://input
* Note that you can override the server default by passing your input to the $server->receive
function, although this does not give you any control over the data that is returned.
If you find these mechanisms too limiting then you can provide your own implementations by passing them as the second parameter of the JsonRpc\Client
and JsonRpc\Server
constructors, as described below.
For reference see the default class at src/JsonRpc/Transport/BasicClient.php
. Your transport class must be instantiable and must contain the following members:
- a
$transport->send
public function returning true or false - a
$transport->output
public property - a
$transport->error
public property
It should look like this:
<?php
class MyClientTransport
{
public $output = '';
public $error = '';
public function send($method, $url, $data, $headers = array())
{
// do stuff to send $data and get the response
...
if ($response)
{
// put the response in $this->output property and return true
$this->output = $response;
return true;
}
else
{
// put the error in $this->error property and return false
$this->error = $error;
return false;
}
}
}
To use your client transport, create it and pass it to the client constructor:
<?php
$transport = new MyClientTransport();
$client = new JsonRpc\Client($url, $transport);
Alternatively you can use the $client->setTransport
method:
<?php
$client = new JsonRpc\Client($url);
$transport = new MyClientTransport();
$client->setTransport($transport);
For reference see the default class at src/JsonRpc/Transport/BasicServer.php
. Your transport class must be instantiable and must contain the following members:
- a
$transport->receive
public function that returns the data received - a
$transport->reply
public function that sends the data and calls exit
It should look like this:
<?php
class MyServerTransport
{
public function receive()
{
// do something to get the received data
return $data;
}
public function reply($data)
{
// do something with the $data
// send the data and call exit
echo $data;
exit;
}
}
Note that it is your responsibility to exit the process. To use your server transport, create it and pass it to the server constructor:
<?php
$transport = new MyServerTransport();
$server = new JsonRpc\Server($methods, $transport);
Alternatively you can use the $server->setTransport
method:
<?php
$server = new JsonRpc\Server($methods);
$transport = new MyServerTransport();
$server->setTransport($transport);