Extends
lithium\core\Object
Converts a `Collection` object to another type of object, or a simple type such as an array.
The supported values of `$format` depend on the format handlers registered in the static
property `Collection::$_formats`. The `Collection` class comes with built-in support for
array conversion, but other formats may be registered.
Once the appropriate handlers are registered, a `Collection` instance can be converted into
any handler-supported format, i.e.: {{{
$collection->to('json'); // returns a JSON string
$collection->to('xml'); // returns an XML string
}}}
_Please note that Lithium does not ship with a default XML handler, but one can be
configured easily._
Parameters
- string $format By default the only supported value is `'array'`. However, additional format handlers can be registered using the `formats()` method.
- array $options Options for converting this collection: - `'internal'` _boolean_: Indicates whether the current internal representation of the collection should be exported. Defaults to `false`, which uses the standard iterator interfaces. This is useful for exporting record sets, where records are lazy-loaded, and the collection must be iterated in order to fetch all objects.
Returns
mixed The object converted to the value specified in `$format`; usually an array or string.Source
public function to($format, array $options = array()) {
$defaults = array('internal' => false);
$options += $defaults;
$data = $options['internal'] ? $this->_data : $this;
if (is_object($format) && is_callable($format)) {
return $format($data, $options);
}
if (isset(static::$_formats[$format]) && is_callable(static::$_formats[$format])) {
$handler = static::$_formats[$format];
$handler = is_string($handler) ? explode('::', $handler, 2) : $handler;
if (is_array($handler)) {
list($class, $method) = $handler;
return $class::$method($data, $options);
}
return $handler($data, $options);
}
foreach (static::$_formats as $key => $handler) {
if (!is_int($key)) {
continue;
}
if (in_array($format, $handler::formats($format, $data, $options))) {
return $handler::to($format, $data, $options);
}
}
}