вторник, 15 января 2013 г.

Phalcon: Set output format for Phalcon-based RESTful API

1. edit .htaccess

AddDefaultCharset UTF-8

<ifmodule mod_rewrite.c="mod_rewrite.c">
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^.]+)$ index.php?_url=/$1&format=json [QSA,L]
    RewriteRule ^([^.]+)\.(\w+)$ index.php?_url=/$1&format=$2 [QSA,L]
</ifmodule>


2. edit index.php
  ...
  $app = new \Phalcon\Mvc\Micro();
  ...
  $app->finish(function () use ($app) {
    // check format
    $format = $app->request->getQuery('format', 'string', 'json');
    switch ($format) {
      case 'json': 
        print(json_encode($app->result->data));
        break;
      case 'xml':
        $xml = new SimpleXMLElement('');
        array_walk_recursive($app->result->data, array ($xml, 'addChild'));
        print $xml->asXML();
        break;
    }
  });
  
3. use api with .json | .xml

$ curl http://site/api/user/1
$ {json: data}
$ curl http://site/api/user/1.json
$ {json: data}
$ curl http://site/api/user/1.xml
$ <xml>data</xml>