那么你使用的不是一堆PHP文件来完成这件事......所以我认为你是在正确的轨道上=)。文章中的实现是可以的,但很古老......是在4年前编写的。我会建议看看Zend_Soap_Server,Zend_Json_Server或Zend_Rest_Server。在我看来,Soap解决方案对于手机来说有点沉重。
只是决定实施和做小规划!
我写了一个web应用程序,后来不得不添加服务层,以便为应用程序添加移动应用程序界面。不幸的是,这不是最初要求的一部分,所以不得不重做很多事情。
我的建议如下:(如果你的web应用和API都在同一个项目):
- 代码的所有应用程序逻辑库或控制器助手。所以,同样的代码可以在主Web应用程序和API层被重用
- 代码在默认模块你的webapp逻辑
- 代码的专用模块的API层称为“API”
- PHPDoc的必须为了完美zend自动生成SMD
对于API使用标准的JSON-RPC 2.0协议,有Android和iPhone的客户端使用它并提供自动发现(SMD类似于WSDL但是用于json)。所有通过GET发送的请求都会显示SMD,其他所有请求都会导致处理请求。
利用Zend_Json_Server为您的API层。 下面是一个功能实例:
<?php
// API Controller Example
class ApiController extends Zend_Controller_Action
{
public function init()
{
parent::init();
$this->getHelper('ViewRenderer')->setNoRender();
}
public function helloWorldAction()
{
$this->_handleRequest('App_Api_HelloWorld');
}
protected function _handleRequest($handlerClassName)
{
//
$this->getHelper('ViewRenderer')->setNoRender();
//
$server = new Zend_Json_Server();
$server->setClass($handlerClassName);
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$cfg = Zend_Registry::get('config');
$req = $this->getRequest();
$reqUrl = $cfg->paths->basehref . $req->getControllerName() . '/' . $req->getActionName();
$server->setTarget($reqUrl)
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();
header('Content-Type: application/json');
echo $smd;
} else {
// handle request
$server->handle();
}
}
}
// HANDLER Class Example
class App_Api_HelloWorld extends App_Api_ApiHandlerAbstract
{
/**
* says "hello world"
*
* @return string
*/
public function hello()
{
return 'hello world';
}
/**
* says "hello $name"
*
* @param string $name
* @return string
*/
public function hello2($name)
{
return "hello $name";
}
/**
*
* @return string
* @throws Exception
*/
public function hello3()
{
throw new Zend_Json_Server_Exception('not allowed');
return '';
}
}
下面是示例请求(I加入按id一些自举魔法拾取会议)
https://domain.com/api/hello-world
{
"session_id": "4ggskr4fhe3lagf76b5tgaiu57",
"method": "hello2",
"params": {
"name" : "Alex"
},
"id": 123
}
评分JSON RPC 2.0 Documentation。
我发现Advanced REST Client谷歌浏览器是开发和测试JSON Web服务的最佳扩展。
为了提高安全性,您可以通过向抽象控制器添加几行代码来限制所有请求,甚至创建安全性controller plugin。
祝你好运。
感谢您的详细解释。 –