This library uses some tricks to intern values so that two distances are always equal to one another, no matter the distance in time or space.
use Withinboredom\Distance;
use Withinboredom\Distance\Unit;
$meter = Distance::from(Unit::Meters, 1);
$centimeters = Distance::from(Unit::Centimeters, 100);
echo $meter === $centimeters ? 'true' : 'false'
// outputs: true
You can ensure nobody will accidentally confuse inches with centimeters or Nautical Miles with Miles:
function moveForward(Distance $distance) { /* move */ }
moveForward(Distance::from(Unit::Miles, 10));
You can convert between units and even perform operations, like sorting and arithmetic:
$meter = Meters(1);
$meter = $meter->multiply(10)->add(Inches(10)); // get 10 meters and 10 inches
echo Centimeters(10) < $meter ? 'true' : 'false';
// output: true
You cannot serialize/deserialize/clone Distance
objects.
However, if you use something like Serde, you can still serialize your value objects:
class Robot {
public function __construct(
#[Field('height_in_centimeters')]
#[DistanceAs(Unit::Centimeters)]
public Distance $height,
) {}
}
$serde = new SerdeCommon(handlers: new \Withinboredom\Distance\SerdeExporter());
$serde->serialize(new Robot(Meters(5)), 'json');
The above will be serialized (and deserialized) from:
{
"height_in_centimeters": 500
}
There are several distance units supported
- Micrometers
- Millimeters
- Centimeters
- Meters
- Kilometers
- Inches
- Feet
- Yards
- Miles
- Furlongs
- Nautical Miles
- Astronomical Units
How far can I go?
The base unit is in micrometers, so on a 64-bit system you can go ~60AU with micrometer accuracy. For reference, Pluto is usually about 40 AU away from the sun.
If you are limited to 32-bit systems, this is not for you. The maximum distance on a 32-bit system is just a couple of meters.
Why does this exist?
I don’t like magic numbers.
How performant is this?
The main overhead is in autoloading and function-call overhead. Thus, if realtime performance is a concern, you might want to stick to magic numbers.
If you wish to create a PR or update the code here:
- Clone the repo
composer install
to install test dependenciesyarn
to install git hooks for formatting- Open in favorite IDE.
Per coding styles are followed.