Server module example

Last updated on
30 April 2025

Here is a commented example of a server module which uses hook_server() to become a server.

<?php
/**
 * Implementation of hook_server_info()
 * required to let services know that this is a server.
 * returns a hashed array
 */
function xmlrpc_server_server_info() {
  return array(
    // #name - display name used in the Services admin pages
    '#name' => 'XMLRPC'
    
    // #path - the path (under '/services/') where the server will
    // handle calls.  This one will be '/services/xmlrpc'
    '#path' => 'xmlrpc'
  );
}

/**
 * Implementation of hook_server()
 * The callback function to handle all requests to the path defined above.
 * This is required
 */
function xmlrpc_server_server() {
  // load in any additional libraries needed
  require_once './includes/xmlrpc.inc';
  require_once './includes/xmlrpcs.inc';
  
  // handle the request, and return the result of the request
  return xmlrpc_server(xmlrpc_server_xmlrpc());
}

/**
 * Implmentation of hook_xmlrpc
 * Specific to this xmlrpc_server module
 * this is how we map an xmlrpc request to the Services module
 */
function xmlrpc_server_xmlrpc() {
  $callbacks = array();
  
  // we find all the services available
  foreach (services_get_all() as $method) {
    $args = array();
    
    // convert the args to be compatible with the Drupal xmlrpc server
    foreach ($method['#args'] as $arg) {
      if (!is_array($arg)) {
        $args[] = $arg;
      }
      else {
        $args[] = $arg['#type'];
      }
    }
    
    // and map each method's callback to the xmlrpc_server_call_wrapper()
    // function. This is explained below.
    $callbacks[] = array(
      $method['#method'], 
      'xmlrpc_server_call_wrapper', 
      array_merge(array($method['#return']), $args),
      $method['#help']);
  }
  return array_merge($defaults, $callbacks);
}

/**
 * XMLRPC callback for each service method
 * Specific to this xmlrpc_server module
 */
function xmlrpc_server_call_wrapper() {
  // we get the server object
  $xmlrpc_server = xmlrpc_server_get();
  
  // and the method name
  $method_name = $xmlrpc_server->message->methodname;
  
  // and the args
  $args = func_get_args();
  
  // and pass this to the services_method_call() function returning the result
  // services_method_call() wraps all service method calls.  Its provides the
  // additional handling of things like api keys and session IDs.  It take a
  // method_name, like "recipe.all" as its first argument, and the method args
  // as its second argument.
  return services_method_call($method_name, $args);
}


?>

Help improve this page

Page status: Not set

You can: