Skip to content

Setup Guide

Jordan Brauer edited this page Dec 10, 2018 · 2 revisions

There are three main classes that make up a UnitConverter.

  • UnitConverter\UnitConverter: The actual unit converter, itself; provides a nice interface for converting units programatically. It depends on a registry, and a calculator.
  • UnitConverter\Registry\UnitRegistry: The unit registry handles the storing, sorting, and displaying of registered units.
  • UnitConverter\Calculator\SimpleCalculator: The calculator(s) (more on alternatives later) handle the actual number crunching for the unit converter, unless a unit has to convert itself with a unique formula, e.g., temperature.

The Unit Registry

First, you'll want to have a list of units that you require conversion for.

For this example, we will be converting an imperial inch, into a metric centimetre, using the built in Centimetre and Inch classes. To start, lets setup our unit converters' registry.

use UnitConverter\Registry\UnitRegistry;
use UnitConverter\Unit\Length\Centimetre;
use UnitConverter\Unit\Length\Inch;

# Start by creating an array of measurements you want to register to the converter.
# Then, we will instantiate a new UnitRegistry and pass the array to it as it's only argument.

$units = [
    new Centimetre,
    new Inch,
];

$registry = new UnitRegistry($units);

The Calculators

As we all know, computers are not the best with decimal values (floats). When converting units of measurement, we often deal with decimal values. Depending on how precise of a result you require, will depend on what sort of calculator implementation suits you.

This package comes bundled with two calculators for you; the SimpleCalculator, and the BinaryCalculator. They both aim to solve two different problems with numbers.

The SimpleCalculator is the default calculator, and will run calculations on integers, floats, and (somtimes) strings, but will not guarantee the best accuracy on results. The BinaryCalculator leverages the PHP bcmath library to perform accurate floating point calculations, the catch being that it's parameters must be strings.

use UnitConverter\Calculator\SimpleCalculator;
use UnitConverter\Calculator\BinaryCalculator;

# We will use the SimpleCalculator for this example, but the BinaryCalculator is setup exactly
# the same way.

$calculator = new SimpleCalculator;

The Unit Converter

The actual unit converter does not do a whole lot, other than provide a nice interface for converting units, and use the registry and calculator in conjuntion.

use UnitConverter\UnitConverter;

# Instantiate the UnitConverter, passing it the registry and calculator.
$converter = new UnitConverter($registry, $calculator);

And presto! You have ourself a configured unit converter component. Store this in your application DI/IOC container for easy acces.

Clone this wiki locally