Zend Framework - 如何创建可在外部和内部访问的API?

Sjw*_*ies 10 zend-framework

我正在寻找创建一个网站,并将在以后创建一个移动应用程序.

我希望能够为网站和应用程序提供相同级别的数据(即书籍列表).我想为此使用API​​,但我很难在网上找到任何示例或体面的文章.

所以我想我的问题是,如果我要通过HTTP创建一个可由移动应用程序访问的JSON"端点"(例如http://www.mysite.com/api/v1.0/json),那么如何访问相同的功能我的Zend应用程序内部?

(显然我不想复制数据库交互'模型'步骤)

Ste*_*hry 4

不幸的是,由于 Zend 确实不是 RESTful,所以最好的选择是 JSON-Rpc。

您可以在控制器中执行此操作,或者您可以在 index.php 之外创建一个 ajax.php 以减少开销,就像这个人在这里所做的那样

基本上,您需要做的就是:

$server = new Zend_Json_Server();
$server->setClass('My_Class_With_Public_Methods');
// I've found that a lot of clients only support 2.0
$server->getRequest()->setVersion("2.0");
if ('GET' == $_SERVER['REQUEST_METHOD']) {
    // Indicate the URL endpoint, and the JSON-RPC version used:
    $server->setTarget('/ajax.php')
           ->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);

    // Grab the SMD
    $smd = $server->getServiceMap();

    // Return the SMD to the client
    header('Content-Type: application/json');
    echo $smd;
    return;
}

$server->handle();
Run Code Online (Sandbox Code Playgroud)

然后在你的布局中的某个地方:

$server = new Zend_Json_Server();
$server->setClass('My_Class_With_Public_Methods');
$smd = $server->getServiceMap();
?>
<script>
$(document).ready(function() {
    rpc = jQuery.Zend.jsonrpc({
        url : <?=json_encode($this->baseUrl('/ajax'))?>
        , smd : <?=$smd?>
        , async : true
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

举例来说,这是该类:

class My_Class_With_Public_Methods {
    /**
      * Be sure to properly phpdoc your methods,
      * the rpc clients like it when you do
      * 
      * @param float $param1
      * @param float $param2
      * @return float
      */
    public function someMethodInThatClass ($param1, $param2) {
        return $param1 + $param2;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地在 javascript 中调用这样的方法:

rpc.someMethodInThatClass(first_param, second_param, {
    // if async = true when you setup rpc,
    // then the last param is an object w/ callbacks
    'success' : function(data) {

    }
    'error' : function(data) {

    }
});
Run Code Online (Sandbox Code Playgroud)

Android / iPhone 上没有很多众所周知的 JSON-rpc 库 - 但我发现这适用于 Android 的 Zend_Json_Server:

http://software.dzhuvinov.com/json-rpc-2.0-base.html

这适用于 iPhone:

http://www.dizzey.com/development/ios/calling-json-rpc-webservice-in-ios/

显然,从这里开始,您可以像 javascript/您的移动应用程序一样使用 My_Class_With_Public_Methods。