1

I want standartise all JSON responses ( something like 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?

Creating a custom JSON response object with Zend Action Helper ContextSwitch - nice way of doing it, but still requires too much code, imho.

Community
  • 1
  • 1
Kirzilla
  • 16,368
  • 26
  • 84
  • 129

1 Answers1

0

IMO you should use a context switch (JSON or your own) and use your preferred way to format your response data structure.

It seems like you are implementing the ajax form validation aren't you ? Maybe you should have a look on this : Zend form ajax validation on submit (and ask google about processAjax())

Community
  • 1
  • 1
LittleBigDev
  • 454
  • 4
  • 23