-
Notifications
You must be signed in to change notification settings - Fork 39
Unit Customization & Extension
This package was built with extensibility in mind. If you have changes you'd like to make to the default units, or add your own custom units, these guides will tell you how to do so.
Customizing and extending the default units that come with this package is incredibly easy. Each unit not only has getters, but has matching setters for reconfiguring it's symbols, and values to suit your data needs.
Here is an example of adjusting a unit's values, for perhaps spelling purposes.
use UnitConverter\Unit\Length\Centimetre as Centimeter;
$centimeter = new Centimeter;
$centimeter->getName(); # centimetre
$centimeter->setName("centimeter");
$centimeter->getName(); # centimeter
Checkout the API documentation for details on all the methods available to units.
You are able to add your own custom units to the unit registry. The unit converter and registry are flexible enough to allow for you to create your own unit of measure classes, or register them on the fly as needed.
The type of measurement you are creating will depend on which base unit you will have to extend. Configure the basic information.
use UnitConverter\Unit\Energy\EnergyUnit;
class Gigawatt extends EnergyUnit
{
protected function configure (): void
{
$this
->setName("gigawatt") # Great Scott, Marty!
->setSymbol("gw")
->setUnits(1.21)
;
}
}
You will want to do this where you are configuring your unit converter (e.g., a DI/IoC container).
# if you have access to the registry directly:
$registry->registerUnit(new Gigawatt);
# if you only have access to the converter:
$converter->getRegistry()->registerUnit(new Gigawatt);
That's it! Your custom unit of measurement is ready to use & will behave exactly as if it were part of the default units provided with this package.