We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Printout changed response content

I'm new in Phalcon and English is not my native language :) I need to change response format depending of parameters, such as xml or json. For this case i use controller method afterExecuteRoute and my action methods usually return an array, but sometimes it can be a string.

public function afterExecuteRoute(Dispatcher $dispatcher) {
   $content = $dispatcher->getReturnedValue();
   $contentType = 'application/json';
   $contentData = [
      'code' => $this->_requestErrorCode,
      'data' => $content,
      'error' => $this->_requestErrorMessage,
   ];
   switch($dispatcher->getParam('format')) {
      case 'xml':
         $contentType = 'application/xml';
         $contentData = ArrayToXml::convert($contentData, 'response');
         break;
      case 'string':
         $contentData = is_string($content) || is_null($content) ? (string) $content : var_export($content, true);
         break;
      default:
         $contentData = json_encode($contentData);
   }
   $this->response->setContentType($contentType, 'utf-8');
   $response = $this->response->setContent($contentData);

   $response->send();
}

In bootstrap file i printout response with echo $application->handle($_SERVER['REQUEST_URI'])->getContent();.

The problem is when action method returns string, i got that string twice. I can understand that because method send() printout current response content. But it doesn't printout content when methods return array. I've changed content from array to string in afterExecuteRoute, but send() doesn't print it out and i need to use echo in bootstrap file. I can't get it why.

I have checked source code of method handle() and was wondered that there is creating a new response object with getting content from getReturnedValue(). In this case i can't get how to change my content in right way. I can change it in bootstrap file, but it looks like a kludge.



32.2k
Accepted
answer

Did you try it with attach an application:beforeSendResponse event?



2.0k

Just tried, it works as expected, thank you.