Using XML_RPC2 with PEAR - Creating an XML-RPC Server
(Page 3 of 4 )
In addition to consuming XML-RPC services, the XML_RPC2 package allows you to easily provide your own services. This will allow you to create and publish APIs for your system, which will be easily consumed from a variety of other languages and platforms. (This isn't your only option; you can provide a REST, SOAP or other API, but we're focusing on XML-RPC here).
As you'll see, creating a server is almost as simple as creating a client:
<?php
require_once('XML/RPC2/Server.php');
/**
* A simple class to use in our server
*
* The doc blocks on each method are important, as the code
* looks at the doc blocks to determine the signature
Unlike the word "server" implies, you don't need to run anything other than your normal web server. The server itself is the PHP class created by XML_RPC2_Server. When you instantiate this, you give it the name of a class to look for the service methods. In this example we use TimeServer. The XML_RPC2_Server::create() method looks at the provided class and generates all the needed method calls for the server. You need to include PHPDoc style comments on the methods of your server class, as the create() call will look at these comments to determine the signature of that method.
We're also providing an options array when we create this server. In this case, we're simply telling it that all the method calls should be prefixed with the string "time." This will allow us to serve up multiple services from the same script, even if they have conflicting method names. We can simplify this on the client side, by also passing a prefix parameter to the create() method of the client.
Once this file is created, we can then turn around and easily call our newly created service!
As you can see, calling a service that we created is just like calling someone else's service. We specify the "prefix" parameter in the options array just as with the server in our example. In this example, I also enabled the debug parameter, so we can get a view into what goes on during our requests. The output, when run, should resemble the following:
***** Request *****
<?xml version="1.0" encoding="iso-8859-1"? ><methodCall><methodName>time.currentTimeStamp</methodName><params> </params></methodCall>***** End Of request *****
<?xml version="1.0" encoding="iso-8859-1"? ><methodCall><methodName>time.toISO8601</methodName><params><param> <value><int>1214159720</int></value></param></params></methodCall>***** End Of request *****
You can see how the Client library bundles up our request and converts the method into time.currentTimeStamp, and the resulting XML response from our server, similarly encoded.