はたはたのメモ

主に勉強したことについてのメモ用ブログです。PHPerを目指しています。Pythonはまりかけ。GitHub: https://github.com/a-japonicus

ZendFrameworkでXML-RPC

ZendFrameworkのXML-RPCの使い方をメモ


XML-RPC用置き場としてxmlrpcモジュールを追加する( http://hatahata-memo.hatenablog.jp/entry/2013/11/20/154753 参照)

xmlrpc処理用クラスを置くservicesディレクトリを作成する(application/mocules/xmlrpc/services)
これでservicesディレクトリ下の Xmlrpc_Service_***** というクラスをオートローダが読み込んでくれる(ディレクトリ名がservices(複数形)、クラス名がService(単数形)なのに注意!)

XML-RPCのテストとして、四則演算メソッドを持つXmlrpc_Service_Calculatorクラスを作成する(http://framework.zend.com/manual/1.12/ja/zend.json.server.html のCalculatorクラスまんま)

<?php
/* application/modules/xmlrpc/services/Calculator.php */
class Xmlrpc_Service_Calculator
{
    /**
     * 2つの変数の合計を返します
     *
     * @param  int $x
     * @param  int $y
     * @return int
     */
    public function add($x, $y)
    {
        return $x + $y;
    }
    /* 以下略 */
}

XML-RPCはコメントを見て型判別を行っているためメソッドのコメントは省略しないこと

indexコントローラにXML-RPCサーバの記述を行う

<?php
/* application/modules/xmlrpc/controllers/IndexController.php */
class Xmlrpc_IndexController extends Zend_Controller_Action
{
    protected $_server = null;

    public function init()
    {
        // viewは非表示
        $this->_helper->viewRenderer->setNoRender(true);
        
        $this->_server = new Zend_XmlRpc_Server();
        // クラス追加
        // Xmlrpc_Service_CalculatorをCalculatorという名前でアクセスする
        $this->_server->setClass('Xmlrpc_Service_Calculator', 'Calculator');
    }

    public function indexAction()
    {
        // POSTのみ許可
        if ('POST' != $_SERVER['REQUEST_METHOD']) {
            echo $this->_server->fault();
            return;
        }
        // 結果表示
        echo $this->_server->handle();
    }
}

XML-RPCのテストを行う
http://zfのアドレス/xmlrpc に次のXMLをPOSTで送る
FireFoxだとHTTP Resource Testが便利

<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>Calculator.add</methodName>
  <params>
    <param>
      <value><int>42</int></value>
    </param>
    <param>
      <value><int>18</int></value>
    </param>
  </params>
</methodCall>

Xmlrpc_Service_Calculatorクラスのaddメソッドが呼ばれ、42+18の結果が返ってくるはず。