5

I'm evaluating frameworks for use with an API, and I'm taking a serious look at PHP Phalcon. It's looking promising - "lean" (load what you need), but with a lot of options.

I'm wondering... is it possible to not use views (templates, rather) with it? Do I have to set up a view, or can I just output .json?

Thanks!

Mr Mikkél
  • 2,577
  • 4
  • 34
  • 52

4 Answers4

7

There is a way in Phalcon to disable view in the action and avoid unnecessary processing:

public function indexAction() {

    $this->view->disable();

    $this->response->setContentType('application/json');
    echo json_encode($your_data);
}
Phantom
  • 1,704
  • 4
  • 17
  • 32
  • 1
    Awesome. Thank you. Probably could put that into an initialize function for the class, perhaps, since none of the actions will need a view. – Mr Mikkél Jul 19 '14 at 22:07
  • 2
    Yes, you can put `disable()` call into `initialize()` controller method, because this method `is executed first, before any action is executed on a controller`: http://docs.phalconphp.com/en/latest/reference/controllers.html#initializing-controllers – Phantom Jul 20 '14 at 04:54
3

Depending on what you want to do you can disable the view as others have suggested and echo json encoded data, or you could use the built in response object as below:

  $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
  $this->response->setContentType('application/json', 'UTF-8');
  $this->response->setJsonContent($data); //where data is an array containing what you want
   return $this->response;

There is also a tutorial in the docs that goes over building a simple REST api

http://docs.phalconphp.com/en/latest/reference/tutorial-rest.html

TommyBs
  • 9,354
  • 4
  • 34
  • 65
0

If you won't be using any views at all you can disable views at the very start.

$app = new \Phalcon\Mvc\Application();
$app->useImplicitView(false);

Even if you do this, I think you still have to set the view DI for the framework to work.

Also, if you want to output json there's a method for that:

$this->response->setJsonContent($dataArray);
$this->response->send();
galki
  • 8,149
  • 7
  • 50
  • 62
-3

Yeah, you can do it, I'm using PHP Phalcon. To ignore view, in your controller your action should be like

public function indexAction() {
   $var = array or other data 
   die(json_encode($var));
}

die(); in controller will not render any parent layout! :)

Michael
  • 321
  • 2
  • 13
  • 2
    I wouldn't really recommend die, Phalcon has plenty of other ways to handle this. Plus it would stop executing meaning if you had any common functionality built into afterExecuteRoute etc. those methods wouldn't fire – TommyBs Jul 19 '14 at 13:12