It allows you to omit templates if you just need to emit JSON string as response.
In your controller, you could do the following:
$this->set(['posts' => $posts]);
$this->set('_serialize', true);
When the view is rendered, the $posts view variable will be serialized
into JSON.
You can also set multiple view variables for serialization. This will create
a top level object containing all the named view variables:
$this->set(compact('posts', 'users', 'stuff'));
$this->set('_serialize', true);
The above would generate a JSON object that looks like:
{"posts": [...], "users": [...]}
You can also set '_serialize' to a string or array to serialize only the
specified view variables.
If you don't use the _serialize, you will need a view template. You can use
extended views to provide layout-like functionality.
You can also enable JSONP support by setting parameter _jsonp to true or a
string to specify custom query string parameter name which will contain the
callback function name.
/** * Initialization hook method. * * @return void */ public function initialize() { parent::initialize(); Hook::applyHelpers($this); }
/** * Returns data to be serialized. * * @param array|string|bool $serialize The name(s) of the view variable(s) that * need(s) to be serialized. If true all available view variables will be used. * @return mixed The data to serialize. */ protected function _dataToSerialize($serialize = true) { $data = parent::_dataToSerialize($serialize); $serializer = $this->getSerializer(); $includes = $this->get('_includes'); $manager = new Manager(); $manager->setSerializer($serializer); if ($includes) { $manager->parseIncludes($includes); } if (is_array($data)) { foreach ($data as $varName => &$var) { $var = $this->transform($manager, $var, $varName); } unset($var); } else { $data = $this->transform($manager, $data); } return $data; }