上一篇Blog记录了通过Controller Plugin根据HTTP ACCEPT选择性地出现不同的模板,RESTful API是通过HTTP METHOD(GET, POST, PUT, DELETE等)来选择执行不同的动作。同样通过Plugin可以将不同的HTTP METHOD分派给不同的Action来处理。修改后的Plugin如下:
<?php
/**
* Choose correct view for RESTful client
*
* @author lht
* @version
*/
final class Restful extends Zend_Controller_Plugin_Abstract {
protected function adjustAction(Zend_Controller_Request_Abstract $request) {
if ($request->getMethod() == "GET") {
$request->setActionName("get");
}elseif ($request->getMethod() == "POST") {
$request->setActionName("post");
}elseif ($request->getMethod() == "PUT") {
$request->setActionName("put");;
}elseif ($request->getMethod() == "DELETE") {
$request->setActionName("delete");;
}
}
protected function adjustView(Zend_Controller_Request_Abstract $request) {
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
if (preg_match('/text\/xml/i', $request->getHeader('Accept'))) {
$this->getResponse()->setHeader('Content-Type', 'text/xml; charset=utf-8');
$viewRenderer->setViewSuffix('pxml');
} elseif (preg_match('/application\/json/i', $request->getHeader('Accept'))) {
$this->getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8');
$viewRenderer->setViewSuffix('pjson');
} elseif (preg_match('/text\/plain/i', $request->getHeader('Accept'))) {
$this->getResponse()->setHeader('Content-Type', 'text/plain; charset=utf-8');
$viewRenderer->setViewSuffix('ptxt');
}
$this->getResponse()->setHeader('X-Action-Name', $request->getActionName(), TRUE);
}
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$this->adjustAction($request);
$this->adjustView($request);
}
}
具体的Controller Action可以如下:
<?php
/**
* UsersController
*
* @author
* @version
*/
class UsersController extends Zend_Controller_Action {
/**
* The default action - show the home page
*/
public function indexAction() {
$this->getAction ();
}
public function getAction() {
$this->view->userId = $this->getUserId();
}
public function postAction() {
$this->view->userId = $this->getUserId();
}
public function putAction() {
$this->view->userId = $this->getUserId();
}
public function deleteAction() {
$this->view->userId = $this->getUserId();
}
protected function getUserId() {
if ($this->_getParam("id")) {
$userId = $this->_getParam("id");
} elseif ($this->_getParam("action") == "index") {
$userId = NULL;
} else {
$userId = $this->_getParam("action");
}
return $userId;
}
}
这样就可以通过http://yourhost.com/users来管理用户;通过http://yourhost.com/users/1来管理user ID=1的用户了。
本文介绍了一种通过HTTP METHOD (GET, POST, PUT, DELETE) 和HTTP ACCEPT头来区分不同请求并返回相应内容类型的RESTful API设计方法。具体实现了根据不同HTTP METHOD调用相应的Action,并依据客户端接受的内容类型设置响应头。
1157

被折叠的 条评论
为什么被折叠?



