cartalyst/converter
Cartalyst Converter is a PHP unit conversion library that makes it easy to convert values between measurement units (length, weight, volume, etc.). Includes extensible unit definitions, fluent API, and helpers to format results for applications and packages.
composer require cartalyst/converterConverter instance and chain conversions:
$converter = new \Cartalyst\Converter\Converter();
$result = $converter->convert(100, 'cm', 'm'); // 1.0
$lengthInches = 24.5;
$lengthCm = $converter->convert($lengthInches, 'in', 'cm');
src/Converter.php source or the examples/ folder for quick start snippets; full Laravel integration is covered in the README under Laravel Integration.$units = [
'product_weight' => [
'g' => 1,
'oz' => 28.3495,
'lb' => 453.592,
],
];
$converter = new Converter($units);
$weight = $converter->convert(16, 'oz', 'g', 'product_weight');
// In a service like OrderProcessor
$displayWeight = $this->converter
->setPrecision(2)
->convert($orderItem->weight, 'g', 'lb')
->format('%.2f lbs');
Converter as a singleton in AppServiceProvider:
$this->app->singleton(\Cartalyst\Converter\Converter::class, function ($app) {
return new \Cartalyst\Converter\Converter([
'custom' => require base_path('config/custom-units.php'),
]);
});
public function setWeightAttribute($value)
{
$this->attributes['weight_grams'] = $this->converter
->convert($value, 'kg', 'g');
}
public function getWeightAttribute($value)
{
return $this->converter->convert($value, 'g', 'kg');
}
'kg' ≠ 'Kg'); define units consistently and validate inputs.hasUnitType() and hasUnit()), especially when accepting arbitrary strings from user input:
if ($converter->hasUnitType('product_weight') && $converter->hasUnit('product_weight', $inputUnit)) {
// proceed
}
setPrecision() affects internal math, while format() uses sprintf-style masks:
$result = $converter->setPrecision(3)
->convert(10.001, 'm', 'km')
->format('%.3f km'); // "0.010 km"
'length' in your custom set replaces default length units. To extend, merge $converter::getDefaultUnits() first.Cartalyst\Converter\ConverterInterface for custom logic (e.g., dynamic exchange rates), or use Converter::extend() for runtime monkey-patching (use sparingly).How can I help you explore Laravel packages today?