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.
public static formats ( string $format, mixed $handler = null ) : mixed | ||
$format | string | A string representing the name of the format that a `Collection` can be converted to. This corresponds to the `$format` parameter in the `to()` method. Alternatively, the fully-namespaced class name of a format-handler class. |
$handler | mixed | If `$format` is the name of a format string, `$handler` should be the function that handles the conversion, either an anonymous function, or a reference to a method name in `"Class::method"` form. If `$format` is a class name, can be `null`. |
return | mixed | Returns the value of the format handler assigned. |