zend-framework – Zend Framework – 如何创建可从外部访问和内
我正在寻找一个网站,并将在以后创建一个移动应用程序.
我想要能够向网站和应用程序提供相同级别的数据(即书籍列表).我想为此使用一个API,但我很努力在线查找任何示例或体面的文章. 所以我想我的问题是,如果我要通过HTTP创建一个移动应用程序可以访问的JSON‘端点(例如http://www.mysite.com/api/v1.0/json),那么如何从我的Zend应用程序内部访问相同的功能? (显然我不想复制数据库交互模型的步骤)
由于Zend真的不是RESTful,不幸的是,最好的选择是JSON-Rpc.
你可以在控制器中执行,或者你可以做一个ajax.php除了你的index.php以减少开销像这个家伙做了here 基本上,你需要做的就是这样做: $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(); 然后在你的布局中的某个地方: $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> 为了举个例子,这是那个类: 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; } } 那么你可以在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) { } }); 对于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/ 从这里开始,您可以使用My_Class_With_Public_Methods与JavaScript /您的移动应用程序相同的方式. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |