mini\Converter\ConverterInterface
abstract
interface
Documentation
Interface for type converters
Converters transform values from one type to another, enabling automatic conversion of route return values, exceptions, and other types to appropriate response formats.
Implementations must:
- Specify input type via getInputType() (may be union like "string|array")
- Specify output type via getOutputType() (single type only)
- Implement supports() to check if input can be converted to target
- Implement convert() to perform the actual transformation
Most applications should register typed closures rather than implementing this interface directly. ClosureConverter wraps closures automatically.
Example implementation:
class JsonableConverter implements ConverterInterface {
public function getInputType(): string {
return Jsonable::class;
}
public function getOutputType(): string {
return ResponseInterface::class;
}
public function supports(mixed $input, string $targetType): bool {
return $input instanceof Jsonable
&& ($targetType === ResponseInterface::class
|| is_subclass_of($targetType, ResponseInterface::class));
}
public function convert(mixed $input, string $targetType): mixed {
$json = $input->toJson();
return new Response(200, ['Content-Type' => 'application/json'], $json);
}
}
However, using a closure is simpler:
$registry->register(function(Jsonable $obj): ResponseInterface {
$json = $obj->toJson();
return new Response(200, ['Content-Type' => 'application/json'], $json);
});
Methods (4)
Get the input type this converter accepts
Get the output type this converter produces
Check if this converter can handle the given input for target type
Convert the input to the target type