Defining a REST Module

What I want is the ability to set any of my modules with a flag that will make all the controllers of that module act as REST controllers. So basically any return values from the controller will be json encoded and returned.

I currently have the following code in my RESTController.

public function afterExecuteRoute(Dispatcher $dispatcher) {
  $data = $dispatcher->getReturnedValue();
  if (!is_array($data)) {
   $message = $data;
   $data = [];
   $data['message'] = $message;
   }
  $response = new Response;
  $response->setJsonContent($data);
  return $response;
}

But what I really would like to do is transfer this code to the Module level somehow. So if for example I have a module called "api". I would like to define it so that the api module always passes back data json encoded.

Also, my other problem with the above is that when doing an HTTP request, what I get back seems to be fine, but when doing tests through CLI, the response value seems to be doubled.



10.2k
edited Aug '16

Not sure I have an absolute answer for you, but my ajax requests don't use a Response object. I basically just json_encode the data I want to return.

    public function getResponse($success = false)
    {
        return [
            "success" => $success,
            "error" => "",
            "data" => []
        ];
    }

    public function respond($response) {
        echo json_encode($response);
        die();
    }

    public function getsomethingAction() {
        $response = $this->getResponse(true);
        $response['data'] = $cache->get('currentorder'); //assign data to whatever... It will be decoded.
        $this->respond($response);
    }