Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

"MVC" without "V", json response

Hi,

I often need to make REST API with Phalcon. So the views are not needed to me. But if I set in controller:

$this->response->setJsonContent($responseData);

I get empty response. So always I need to do one more step:

return $this->response;

Maybe there is some easy fix/hack to not try to render views if json response are set?

Real code example which I want to simplify:


<?php

use Phalcon\Http\Response;

class AjaxController extends ControllerBase
{
    public function insuranceAction()
    {
        $insurance = $this->request->get('insurance');
        $this->session->set('insurance', $insurance === 'true');
        $response = new Response();

        $response->setJsonContent([
            'status' => 'ok',
            'insurance' => $insurance,
        ]);

        return $response;
    }
}

Regards

 $this->response->setContentType("application/json");
    return $this->response->setJsonContent([]);

      $this->response->send();
      $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
edited 12d ago

Just use Phalcon Micro for RESTful API's.

Phalcon micro has no file structure. If you need to have a lot of endpoints, then you will have a headache. Thats why I prefer default phalcon file structure.

My idea is to avoid calling views if json content is already set to response. Actually do we really need to fetch views layer if any content already set to response?

edited 11d ago

Are you referring to default routes mapping, e.g. controller/action defaults?

There is MicroCollection which is great for REST API's.

The only thing Micro lacks is a Dispatcher. But if you structure few things well you can really live w/o it.

Take a look at the link I posted in a previous post.

This is the method I have in my base controller:

protected function outputJSON($what_to_output){
    $this->view->disable();
    header('Content-type: text/json');
    echo json_encode($what_to_output);
    exit();
}

This thread also has some good ideas: https://forum.phalconphp.com/discussion/22/the-best-way-for-json-response-



133.9k
Accepted
answer

You can just do:

return $this->response->setJsonContent($responseData);

This is what i do in 99% of cases.