新答案:
我想出了一個似乎很好的模式。它解決了您所有的擔憂: 這裏是我想出的縮小版本:
首先,我們需要我們自己的控制器。這個控制器將有一個服務,通過它代理服務的任何行動請求,如果他們沒有定義:
abstract class App_Rest_Controller extends Zend_Controller_Action
{
/**
* @var App_Rest_Service_Abstract
*/
protected $_service;
public function __call($methodName, $args)
{
if ('Action' == substr($methodName, -6)) {
$action = substr($methodName, 0, strlen($methodName) - 6);
return $this->_service()->$action();
}
return parent::__call($methodName, $args);
}
}
現在它的時間爲服務。我們延長動作助手摘要使:
- 我們不得不請求對象
- 直接訪問,我們可以輕鬆地從任何控制器
這將起到對之間一去調用服務應用程序和數據的實際存儲。
abstract class App_Rest_Service_Abstract extends Zend_Controller_Action_Helper_Abstract
{
/*
* @var App_Rest_Storage_Interface
*/
protected $_storage;
public function __call($methodName, $args)
{
if (!method_exists($this->getStorage(), $methodName)) {
throw new App_Rest_Service_Exception(sprintf('The storage does not have the method "%s"', $methodName));
}
switch ($methodName) {
case 'get':
case 'put':
case 'delete':
//if id param isnot set, throw an exception
if (FALSE === ($id = $this->getRequest()->getParam('id', FALSE))) {
throw new App_Rest_Service_Exception(sprintf('Method "%s" expects an id param, none provided', $methodName));
}
$iterator = $this->getStorage()->$methodName($id, $this->getRequest()->getParams());
break;
case 'index':
case 'post':
default:
//if index, post or not a tradition RESTful request, the function must expect the first and only argument to be an array
$iterator = $this->getStorage()->$methodName($this->getRequest()->getParams());
break;
}
return $this->_getResult($iterator);
}
protected function _getResult($iterator)
{ /*
* write your own, in my case i make a paginator and then
* either return it or send data via the json helper
*
/*
}
現在爲接口。這將完成存儲,修改和返回數據的實際工作。使用它作爲界面的美妙之處在於無論您使用什麼模型圖層,都可以輕鬆實現它。我創建了一個簡單的Zend_Form(用於驗證)和一個Zend_Db_Table用於實際數據的抽象存儲。但你也可以在任何對象上實現它。
interface App_Rest_Storage_Interface extends Zend_Validate_Interface
{
public function index(array $params = NULL);
public function get($id, array $params = NULL);
public function post(array $params);
public function put($id, array $params);
public function delete($id, array $params);
}
現在可以在您的網站的任何地方進行操作。假設你有一個「客戶」服務。任何內部控制其作爲
$customer = $this->_helper->helper->customers->get(1);
其他地方一樣簡單(比方說一個視圖助手):
Zend_Controller_Action_HelperBroker::getStaticHelper('customers')->get(1)
我希望這有助於。它對我來說很好。
@ Venu Gopal T親愛的接受他人提出的問題。通過點擊每個答案 – 2011-04-29 12:08:22
ha的勾號標記,對!謝謝 – Venu 2011-04-29 12:10:34