那麼你使用的不是一堆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。
祝你好運。
感謝您的詳細解釋。 –