This component is always attached to any controller and automatically takes care of rendering the right type of view when json or xml are requested. It checks "Accept" request header, parses url extensions (.json/.xml) and tells the controller to use JsonView or XmlView.

For example in a frontend app: calling from a client an url like http://example.com/sample.json or using jQuery

$.ajax({
	url: '/other_sample',
	type: 'get',
	dataType: 'json'
});

we force ResponseHandler to respond as json to client.

JsonView and XmlView views check if a special key named _serialize is in viewVars and  serialize all viewVars found in it to present the payload to client.

Following the example above

public function otherSample() {
	$langs = array('eng' => 'English', 'ita' => 'Italian');
	$this->set({
		'langs' => $langs,
		'_serialize' => array('langs')
	});
}

outputs to client

{
	"langs": {
		"eng": "English",
		"ita": "Italian"
	}
}

Sending Headers

The ResponseHandler component is also very useful to send http status code to clients, for example

$this->ResponseHandler->sendStatus(400);

Sends a "Bad Request" header.

or to send any generic header

// send content type image/png header to client
$this->RequestHandler->sendHeader('Content-Type: image/png');
// the same as above
$this->RequestHandler->sendHeader('Content-Type', 'image/png');

Setting Type

To force a specific type (json or xml)

$this->ResponseHandler->setType('json');

or do it globally

public $components = array(
	'ResponseHandler' => array('type' => 'json')
);

Disabling Automatic Response

If you don't want to use ResponseHandler you can disable it in any method of your controller

$this->ResponseHandler->enabled = false;

or globally

public $components = array(
	'ResponseHandler' => array('enabled' => false)
);

Pay attention that disabling ResponseHandler you lose the magic json/xml handling, you have to manage it manually.