public static method

For media types registered in $_handlers which include an 'encode' setting, encodes data according to the specified media type.


  • mixed $handler

    Specifies the media type into which $data will be encoded. This media type must have an 'encode' setting specified in Media::$_handlers. Alternatively, $type can be an array, in which case it is used as the type handler configuration. See the type() method for information on adding type handlers, and the available configuration keys.

  • mixed $data

    Arbitrary data you wish to encode. Note that some encoders can only handle arrays or objects.

  • object $response

    A reference to the Response object for this dispatch cycle.



Returns the result of $data, encoded with the encoding configuration specified by $type, the result of which is usually a string.


This method can be filtered.


	public static function encode($handler, $data, &$response = null) {
		$params = ['response' => &$response] + compact('handler', 'data');

		return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
			$data = $params['data'];
			$handler = $params['handler'];
			$response =& $params['response'];
			$handler = is_array($handler) ? $handler : static::handlers($handler);

			if (!$handler || empty($handler['encode'])) {
				return null;

			$cast = function($data) {
				if (!is_object($data)) {
					return $data;
				return method_exists($data, 'to') ? $data->to('array') : get_object_vars($data);

			if (!isset($handler['cast']) || $handler['cast']) {
				$data = is_object($data) ? $cast($data) : $data;
				$data = is_array($data) ? array_map($cast, $data) : $data;
			$method = $handler['encode'];
			return is_string($method) ? $method($data) : $method($data, $handler, $response);