【问题标题】:Custom standartised JSON response for Zend FrameworkZend 框架的自定义标准化 JSON 响应
【发布时间】:2012-09-12 14:18:18
【问题描述】:

我想要标准化所有 JSON 响应(类似于 Standardised JSON response from views )。 这是 JSON 响应示例

{
    "status" : "failure",
    "errors" : {
        "name" : [ "Error text 1", "Error text 2" ],
        "email" : [ "Email error text" ]
    }
}

这是实现我的标准化 JSON 响应的类

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());
    }

}

一切都很好,但是使用这个类真的很痛苦。

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;     
    }

}

我是 Zend 框架的真正菜鸟。 将 JsonResponse 包装到的最佳方式是什么?

  • 帮手
  • 扩展Zend_Controller_Response_Abstract
  • 新的上下文切换
  • 在Form中实现

最好的方法是什么?

Creating a custom JSON response object with Zend Action Helper ContextSwitch - 不错的方法,但仍然需要太多代码,恕我直言。

【问题讨论】:

    标签: php json zend-framework


    【解决方案1】:

    IMO 您应该使用上下文切换(JSON 或您自己的)并使用您喜欢的方式来格式化您的响应数据结构。

    您似乎正在实施 ajax 表单验证,不是吗?也许你应该看看这个:Zend form ajax validation on submit(并向谷歌询问processAjax())

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多