Custom standartised JSON response for Zend Framework

I want standartise all JSON responses ( something like https://stackoverflow.com/questions/6607443/standardised-json-response-from-views ). Here is JSON response example { "status" : "failure", "errors" : { "name" : [ "Error text 1", "Error text 2" ], "email" : [ "Email error text" ] } } And here is class implementing my standartised JSON response class JsonResponse { protected $_errors = array(); public function addError($key, $value) { $this->_errors[$key][] = $value; return $this; } public function setFormErrors(Zend_Form_Abstract $form) { $this->_errors = $form->getErrors(); return $this; } public function __toArray() { if (!empty($this->errors)) { return array( 'status' => 'fail', 'errors' => $errors, ); } return array( 'status' => 'success', ); } public function __toString() { return json_encode($this->__toArray()); } } Everything is great, but using this class is real pain in the ass. class App_Controller extends Zend_Action_Controller { public function submitAction() { $form = new App_Form(); $form->isValid($this->getRequest()->getPost()); //disabling displaying layout $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $response = new JsonResponse(); $response->setFormErrors($form); echo $response; } } I'm real noob in Zend Framework. What is the best way to wrap **JsonResponse** to? - helper - extend `Zend_Controller_Response_Abstract` - new context switch - implement in `Form` What is the best approach? https://stackoverflow.com/questions/5231584/creating-a-custom-json-response-object-with-zend-action-helper-contextswitch - nice way of doing it, but still requires too much code, imho.

以上就是Custom standartised JSON response for Zend Framework的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JSON 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏