khaledalam / unit
A PHP library for unit conversions and quantity operations
Requires
- php: ^8.2
Requires (Dev)
- phpunit/phpunit: ^11.4
README
PHP Units & Dimensions Library
A lightweight, type-safe PHP library for working with quantities, units, and dimensional analysis. Inspired by scientific computing needs, this library lets you define units, register them globally, perform arithmetic with dimension checking, and convert across compatible units.
Features
- Immutable objects
- Dimensionally-aware arithmetic (
add
,subtract
,multiply
,divide
) - Automatic conversion between compatible units (e.g., cm to m)
- Support for compound units (e.g., m/s, kg⋅m²/s²)
- Enum-powered unit naming (
Name
enum) - Custom unit registry
Installation
composer require khaledalam/unit
Basic Usage
<?php // test.php // __construct(string $name, Name|string $symbol, float $factor, Dimension $dimension) require __DIR__ . '/vendor/autoload.php'; use KhaledAlam\Unit\Unit; use KhaledAlam\Unit\Name; use KhaledAlam\Unit\Dimension; use KhaledAlam\Unit\Quantity; use KhaledAlam\Unit\UnitRegistry; // Register base units UnitRegistry::register(new Unit(Name::M->value, Name::M, 1.0, new Dimension(['L' => 1]))); UnitRegistry::register(new Unit(Name::CM->value, Name::CM, 0.01, new Dimension(['L' => 1]))); // Create quantities $length1 = Quantity::from(2.0, 'm'); $length2 = Quantity::from(100.0, 'cm'); // Add quantities (auto conversion) $sum = $length1->add($length2); // Result: 3.0 m echo $sum; // "3 m" ?>
output:
% php main.php 3 m
Arithmetic Support
$velocity = Quantity::from(10, 'm')->divide(Quantity::from(2, 's')); // 5 m/s $area = Quantity::from(2, 'm')->multiply(Quantity::from(3, 'm')); // 6 m²
All operations return new Quantity
objects with proper dimensions and units.
Unit Registration
Define and register your own units:
UnitRegistry::register(new Unit('inch', Name::INCH, 0.0254, new Dimension(['L' => 1])));
Exception Handling
Operations on incompatible dimensions will throw an exception:
$mass = Quantity::from(5, 'kg'); $time = Quantity::from(3, 's'); $mass->add($time); // InvalidArgumentException
Running Tests
This project uses PHP-internal's built-in run-tests.php
format.
php run-tests.php tests/ --show-diff
Or
./vendor/bin/phpunit \ --configuration phpunit.xml.dist \ --testsuite=unit
Each test follows .phpt
format and validates expected behavior.
Project Structure
src/
└── Unit/
├── Quantity.php
├── Unit.php
├── Dimension.php
├── UnitRegistry.php
└── Name.php (enum)
tests/
├── add/
├── convert/
├── divide/
└── ...
About
Built by Khaled Alam to bring better scientific and data modeling features to PHP developers.