Skip to content

Advanced functionality

johnstevenson edited this page Sep 26, 2012 · 20 revisions

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 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.

Client Transport

For reference you can see the default class at src/JsonRpc/Transport/BasicClient.php. Your transport class must be instantiable and must contain the following:

  • 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
      $this->output = $response; 

      return true;
    }
    else
    {
      // put the error in $this->error property
      $this->error = $error;

      return false;
    }

  }

}

To use your class, 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);

Server Transport

Your transport class must be instantiable and must contain the following:

  • a $transport->receive public function that returns the data received
  • a $transport->send public function that sends the data

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
    
    echo $data;
    exit;
  }

}
Clone this wiki locally