CodeIgniter 用户指南 版本 1.7.2

编辑文档、查看近期更改请 登录注册  找回密码
查看原文

XML-RPC 和 XML-RPC 服务器类

CodeIgniter 的 XML-RPC  类允许你发送请求到另一个服务器, 或者建立一个你自己的XML-RPC服务器来接受请求.

什么是XML-RPC?

这是一个非常简单的两台计算机使用XML通过互联网进行通信的方法. 一台计算机 , 我们称之为 客户端 , 发送一个XML-RPC 请求 给另外一台计算机 , 我们称之为 服务器. 当服务器收到请求并加以处理,然后将 结果 返回给客户端.

例如,使用 MetaWeblog 的 API(应用程序接口) , 一个XML-RPC客户端(通常是桌面发布工具)会发送一个请求到运行在你网站的XML-RPC服务端. 这个请求有可能是要发布一篇新的网志,或者是要修改已存在的网志. 当XML-RPC服务器接收到请求,将检验请求并且决定调用何种类/方法来处理请求.一旦处理完毕,服务器将返回一个响应信息.

如果要查看更详细的规范,你可以浏览 XML-RPC 网站.

初始化类

像CodeIgniter的大多数类一样, XML-RPC 和 XML-RPCS 类 在你的控制器中调用 $this->load->library 方法来进行初始化:

使用以下代码载入XML-RPC类库:

$this->load->library('xmlrpc');

一旦XML-RPC类被载入, XML-RPC 库的对象就可以使用了: $this->xmlrpc

使用下面的方法载入 XML-RPC 服务器类:

$this->load->library('xmlrpc');
$this->load->library('xmlrpcs');

一旦加入,可以通过 $this->xmlrpcs 使用 xml-rpcs 库对象: $this->xmlrpcs

注意:  使用 XML-RPC 服务器,必须同时载入 XML-RPC 类和 XML-RPC 服务器类。

发送 XML-RPC 请求

发送一个请求到 XML-RPC 服务器,需指定如下信息:

下面是一个简单的例子,它发送一个简单的 Weblogs.com ping 到Ping-o-Matic

$this->load->library('xmlrpc');

$this->xmlrpc->server('http://rpc.pingomatic.com/', 80);
$this->xmlrpc->method('weblogUpdates.ping');

$request = array('My Photoblog', 'http://www.my-site.com/photoblog/');
$this->xmlrpc->request($request);

if ( ! $this->xmlrpc->send_request())
{
    echo $this->xmlrpc->display_error();
}

说明

以上代码初始化XML-RPC类,设置了服务器的URL和要调用的方法(weblogUpdates.ping). 请求(在此例中为你网站的标题和URL)被放在一个数组中使用 request() 函数传输、编译。最后,整个请求发出,如果send_request()方法返回 false,我们将显示XML-RPC 服务器发回的错误信息。

 

请求剖析

一个 XML-RPC 请求只是你发送到 XML-RPC 服务器的数据。请求中的每个数据片断也被称为请求参数。在上面的示例中,有两个参数:你网站的URL和标题。当 XML-RPC 服务器接到你的请求,服务器会寻找请求参数。

请求参数必须放在数组中传输,每个参数可以是七种数据类型中的任一种(字符串,数字,日期,等等)。如果你的参数是字符串外的其它类型,则必须在请求数组中包含数据类型。

下面是一个包含三个参数的简单数组示例:

$request = array('John', 'Doe', 'www.some-site.com');
$this->xmlrpc->request($request);

如果你使用除字符串以外的其它类型,或有几种不同的数据类型,你需要将每个参数单独放到一个数组中,并在数组第二个位置给出数据类型。

$request = array (
                   array('John', 'string'),
                   array('Doe', 'string'),
                   array(FALSE, 'boolean'),
                   array(12345, 'int')
                 );
$this->xmlrpc->request($request);
数据类型 中包括完成的数据类型列表。

创建 XML-RPC 服务器

XML-RPC 服务扮演着交通警察的角色,等待进入的请求,并将它们转到恰当的函数进行处理。

To create your own XML-RPC server involves initializing the XML-RPC Server class in your controller where you expect the incoming request to appear, then setting up an array with mapping instructions so that incoming requests can be sent to the appropriate class and method for processing.

Here is an example to illustrate:

$this->load->library('xmlrpc');
$this->load->library('xmlrpcs');

$config['functions']['new_post'] = array('function' => 'My_blog.new_entry'),
$config['functions']['update_post'] = array('function' => 'My_blog.update_entry');
$config['object'] = $this;

$this->xmlrpcs->initialize($config);
$this->xmlrpcs->serve();

The above example contains an array specifying two method requests that the Server allows. The allowed methods are on the left side of the array. When either of those are received, they will be mapped to the class and method on the right.

The 'object' key is a special key that you pass an instantiated class object with, which is necessary when the method you are mapping to is not part of the CodeIgniter super object.

In other words, if an XML-RPC Client sends a request for the new_post method, your server will load the My_blog class and call the new_entry function. If the request is for the update_post method, your server will load the My_blog class and call the update_entry function.

The function names in the above example are arbitrary. You'll decide what they should be called on your server, or if you are using standardized APIs, like the Blogger or MetaWeblog API, you'll use their function names.

Processing Server Requests

When the XML-RPC Server receives a request and loads the class/method for processing, it will pass an object to that method containing the data sent by the client.

Using the above example, if the new_post method is requested, the server will expect a class to exist with this prototype:

class My_blog extends Controller {

    function new_post($request)
    {

    }
}

The $request variable is an object compiled by the Server, which contains the data sent by the XML-RPC Client. Using this object you will have access to the request parameters enabling you to process the request. When you are done you will send a Response back to the Client.

Below is a real-world example, using the Blogger API. One of the methods in the Blogger API is getUserInfo(). Using this method, an XML-RPC Client can send the Server a username and password, in return the Server sends back information about that particular user (nickname, user ID, email address, etc.). Here is how the processing function might look:

class My_blog extends Controller {

    function getUserInfo($request)
    {
        $username = 'smitty';
        $password = 'secretsmittypass';

        $this->load->library('xmlrpc');
    
        $parameters = $request->output_parameters();
    
        if ($parameters['1'] != $username AND $parameters['2'] != $password)
        {
            return $this->xmlrpc->send_error_message('100', 'Invalid Access');
        }
    
        $response = array(array('nickname'  => array('Smitty','string'),
                                'userid'    => array('99','string'),
                                'url'       => array('http://yoursite.com','string'),
                                'email'     => array('jsmith@yoursite.com','string'),
                                'lastname'  => array('Smith','string'),
                                'firstname' => array('John','string')
                                ),
                         'struct');

        return $this->xmlrpc->send_response($response);
    }
}

Notes:

The output_parameters() function retrieves an indexed array corresponding to the request parameters sent by the client. In the above example, the output parameters will be the username and password.

If the username and password sent by the client were not valid, and error message is returned using send_error_message().

If the operation was successful, the client will be sent back a response array containing the user's info.

Formatting a Response

Similar to Requests, Responses must be formatted as an array. However, unlike requests, a response is an array that contains a single item. This item can be an array with several additional arrays, but there can be only one primary array index. In other words, the basic prototype is this:

$response = array('Response data', 'array');

Responses, however, usually contain multiple pieces of information. In order to accomplish this we must put the response into its own array so that the primary array continues to contain a single piece of data. Here's an example showing how this might be accomplished:

$response = array (
                   array(
                         'first_name' => array('John', 'string'),
                         'last_name' => array('Doe', 'string'),
                         'member_id' => array(123435, 'int'),
                         'todo_list' => array(array('clean house', 'call mom', 'water plants'), 'array'),
                        ),
                 'struct'
                 );

Notice that the above array is formatted as a struct. This is the most common data type for responses.

As with Requests, a response can be one of the seven data types listed in the Data Types section.

Sending an Error Response

If you need to send the client an error response you will use the following:

return $this->xmlrpc->send_error_message('123', 'Requested data not available');

The first parameter is the error number while the second parameter is the error message.

Creating Your Own Client and Server

To help you understand everything we've covered thus far, let's create a couple controllers that act as XML-RPC Client and Server. You'll use the Client to send a request to the Server and receive a response.

The Client

Using a text editor, create a controller called xmlrpc_client.php. In it, place this code and save it to your applications/controllers/ folder:

Note: In the above code we are using a "url helper". You can find more information in the Helpers Functions page.

The Server

Using a text editor, create a controller called xmlrpc_server.php. In it, place this code and save it to your applications/controllers/ folder:

Try it!

Now visit the your site using a URL similar to this:

example.com/index.php/xmlrpc_client/

You should now see the message you sent to the server, and its response back to you.

The client you created sends a message ("How's is going?") to the server, along with a request for the "Greetings" method. The Server receives the request and maps it to the "process" function, where a response is sent back.

Using Associative Arrays In a Request Parameter

If you wish to use an associative array in your method parameters you will need to use a struct datatype:

$request = array(
                 array(
                       // Param 0
                       array(
                             'name'=>'John'
                             ),
                             'struct'
                       ),
                       array(
                             // Param 1
                             array(
                                   'size'=>'large',
                                   'shape'=>'round'
                                   ),
                             'struct'
                       )
                 );
$this->xmlrpc->request($request);

You can retrieve the associative array when processing the request in the Server.

$parameters = $request->output_parameters();
$name = $parameters['0']['name'];
$size = $parameters['1']['size'];
$size = $parameters['1']['shape'];

XML-RPC Function Reference

$this->xmlrpc->server()

Sets the URL and port number of the server to which a request is to be sent:

$this->xmlrpc->server('http://www.sometimes.com/pings.php', 80);

$this->xmlrpc->timeout()

Set a time out period (in seconds) after which the request will be canceled:

$this->xmlrpc->timeout(6);

$this->xmlrpc->method()

Sets the method that will be requested from the XML-RPC server:

$this->xmlrpc->method('method');

Where method is the name of the method.

$this->xmlrpc->request()

Takes an array of data and builds request to be sent to XML-RPC server:

$request = array(array('My Photoblog', 'string'), 'http://www.yoursite.com/photoblog/');
$this->xmlrpc->request($request);

$this->xmlrpc->send_request()

The request sending function. Returns boolean TRUE or FALSE based on success for failure, enabling it to be used conditionally.

$this->xmlrpc->set_debug(TRUE);

Enables debugging, which will display a variety of information and error data helpful during development.

$this->xmlrpc->display_error()

Returns an error message as a string if your request failed for some reason.

echo $this->xmlrpc->display_error();

$this->xmlrpc->display_response()

Returns the response from the remote server once request is received. The response will typically be an associative array.

$this->xmlrpc->display_response();

$this->xmlrpc->send_error_message()

This function lets you send an error message from your server to the client. First parameter is the error number while the second parameter is the error message.

return $this->xmlrpc->send_error_message('123', 'Requested data not available');

$this->xmlrpc->send_response()

Lets you send the response from your server to the client. An array of valid data values must be sent with this method.

$response = array(
                 array(
                        'flerror' => array(FALSE, 'boolean'),
                        'message' => "Thanks for the ping!")
                     )
                 'struct');
return $this->xmlrpc->send_response($response);

数据类型

According to the XML-RPC spec there are seven types of values that you can send via XML-RPC:

 

翻译贡献者: Hex, ianyang, sydcurie, wanglinqiang
最后修改: 2009-09-20 01:04:14