baks-dev/reference-measurement
Installation:
composer require baks-dev/reference-measurement
Ensure your project uses PHP 8.4+ (check composer.json and .php-version).
First Use Case: Import the package and create a measurement instance:
use BaksDev\ReferenceMeasurement\Measurement;
$length = new Measurement('10', 'm'); // 10 meters
echo $length->getValue(); // 10
echo $length->getUnit(); // 'm'
Key Classes to Explore:
Measurement: Core class for handling values and units.Unit: Enum-like class for predefined units (e.g., Unit::METER, Unit::KILOGRAM).Converter: For unit conversions (e.g., meters ↔ feet).Where to look first:
src/Measurement.php (core logic).src/Unit.php (supported units and validation).src/Converter.php (conversion logic).// Valid creation
$mass = new Measurement('5', 'kg'); // Valid (kilogram exists)
// Invalid creation (throws \InvalidArgumentException)
try {
$invalid = new Measurement('5', 'xyz'); // 'xyz' is not a supported unit
} catch (\InvalidArgumentException $e) {
// Handle error (e.g., log or return user-friendly message)
}
use BaksDev\ReferenceMeasurement\Converter;
$converter = new Converter();
$feet = $converter->convert($length, 'ft'); // Converts 10m to ~32.8084ft
use BaksDev\ReferenceMeasurement\Unit;
// Check if a unit exists
if (Unit::has('km')) {
$distance = new Measurement('1.5', 'km');
}
// Get all length units
$lengthUnits = Unit::getLengthUnits(); // ['m', 'km', 'cm', ...]
use Illuminate\Database\Eloquent\Model;
use BaksDev\ReferenceMeasurement\Measurement;
class Product extends Model {
protected $casts = [
'weight' => Measurement::class, // Casts to Measurement object
];
public function setWeightAttribute($value) {
$this->attributes['weight'] = new Measurement($value, 'kg');
}
public function getWeightInPoundsAttribute() {
return (new Converter())->convert($this->weight, 'lb');
}
}
Tip: Use Laravel’s Attribute Casting to automatically convert database values to Measurement objects.
$measurements = [
new Measurement('1', 'm'),
new Measurement('2', 'km'),
];
$converted = array_map(
fn($m) => (new Converter())->convert($m, 'ft'),
$measurements
);
Unit Validation Strictness:
'kG' or 'M'). Always validate user input:
if (!Unit::has($userInputUnit)) {
throw new \InvalidArgumentException("Unsupported unit: {$userInputUnit}");
}
Floating-Point Precision:
$converted = $converter->convert($measurement, 'ft');
$rounded = round($converted->getValue(), 2); // e.g., 32.81ft
Immutable Objects:
Measurement objects are immutable. To "modify" them, create a new instance:
$newMeasurement = new Measurement($measurement->getValue(), 'ft');
Laravel Eloquent Quirks:
Attribute Casting (as shown above) or manually serialize:
$measurement->serialize(); // Returns string like "10|m"
Measurement::deserialize('10|m'); // Reconstructs object
Missing Units:
Unit if needed (see Extension Points).Check Supported Units:
dd(Unit::all()); // List all supported units
Conversion Debugging:
$converter = new Converter();
$baseValue = $measurement->getValue();
$convertedValue = $converter->convert($measurement, 'ft')->getValue();
logger()->debug("Converted {$baseValue} {$measurement->getUnit()} to {$convertedValue} ft");
Error Handling:
Measurement creation in a try-catch to handle invalid units gracefully:
try {
$measurement = new Measurement($value, $unit);
} catch (\InvalidArgumentException $e) {
return response()->json(['error' => 'Invalid unit'], 400);
}
Adding Custom Units:
Unit class or create a custom enum. Example:
// In a service provider or config file
Unit::addCustomUnit('custom', 'CustomUnit', ['base_unit' => 'm', 'conversion_factor' => 0.1]);
Custom Converters:
ConverterInterface to add domain-specific conversions:
class CustomConverter implements ConverterInterface {
public function convert(Measurement $measurement, string $targetUnit): Measurement {
// Custom logic here
}
}
Laravel Service Provider:
// In AppServiceProvider
$this->app->bind(Measurement::class, fn() => new Measurement(...));
$this->app->bind(Converter::class, fn() => new Converter());
Localization:
Unit::setLabel('m', 'метр'); // Russian label for meter
How can I help you explore Laravel packages today?