上一篇Blog记录了通过Controller Plugin根据HTTP ACCEPT选择性地出现不同的模板,RESTful API是通过HTTP METHOD(GET, POST, PUT, DELETE等)来选择执行不同的动作。同样通过Plugin可以将不同的HTTP METHOD分派给不同的Action来处理。修改后的Plugin如下:
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可以如下:
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的用户了。