lithium\util\Collection::formats()
Accessor method for adding format handlers to instances and subclasses of Collection.
The values assigned are used by Collection::to() to convert Collection instances into
different formats, i.e. JSON.
This can be accomplished in two ways. First, format handlers may be registered on a case-by-case basis, as in the following:
Collection::formats('json', function($collection, $options) {
return json_encode($collection->to('array'));
});
// You can also implement the above as a static class method, and register it as follows:
Collection::formats('json', '\my\custom\Formatter::toJson');
Alternatively, you can implement a class that can handle several formats. This class must implement two static methods:
A
formats()method, which returns an array indicating what formats it handles.A
to()method, which handles the actual conversion.
Once a class implements these methods, it may be registered per the following:
Collection::formats('\lithium\net\http\Media');
For reference on how to implement these methods, see the Media class.
Once a handler is registered, any instance of Collection or a subclass can be converted to
the format(s) supported by the class or handler, using the to() method.
Parameters
-
string
$formatA string representing the name of the format that a
Collectioncan be converted to. This corresponds to the$formatparameter in theto()method. Alternatively, the fully-namespaced class name of a format-handler class. -
mixed
$handlerIf
$formatis the name of a format string,$handlershould be the function that handles the conversion, either an anonymous function, or a reference to a method name in"Class::method"form. If$formatis a class name, can benull.
Returns
mixedReturns the value of the format handler assigned.
Source
public static function formats($format, $handler = null) {
if ($format === false) {
return static::$_formats = ['array' => 'lithium\util\Collection::toArray'];
}
if ($handler === null && class_exists($format)) {
return static::$_formats[] = $format;
}
return static::$_formats[$format] = $handler;
}