Skip to content

Usage Guide

Jordan Brauer edited this page Dec 10, 2018 · 1 revision

Using the component is really easy. We'll go through the features one by one.

Converting Units

The first and most obvious feature is the ability to convert units. Using the configured converter we set up in the examples above, we can convert 1 inch to centimetres using the three methods, convert(), from(), and to(). They're used like so,

# Using the converter we constructed in our setup example we will convert 1 inch into
# centimetres (which is 2.54cm).

$conversion = $converter->convert(1)->from("in")->to("cm");

# Dumping the result will show us that the conversion worked as expected
var_dump($conversion); # (float) 2.54

Easy as pie! Lets break it down though.

convert(int|float|string $value)

The convert methods takes the value that you are converting. Simple as that.

If you are using the SimpleCalculator, you can pass your value as any type. If you're using the BinaryCalculator, you can only pass strings.

from(string $symbol)

The from method takes the symbol of the unit of measure paired with your value passed to convert. To get the symbol of a unit dynamically, call the getSymbol() method on a unit.

to(string $symbol)

The to method does exactly what the from method does, except that it takes the symbol of the unit you are converting to.

It must called as the last method in the chain. It returns the result of the conversion from the calculator.

all()

The all method does exactly what the to method does, except that it takes no arguments & instead of returning a single value, it returns all possible conversions in an associative array.

Just like the to method, it must called as the last method in the chain.

$converter->convert(1)->from("in")->all();

Would produce the following;

array:15 [
  "au" => 0.0
  "cm" => 2.54
  "dm" => 0.25
  "ft" => 0.08
  "h" => 0.25
  "km" => 0.0
  "ly" => 0.0
  "m" => 0.03
  "um" => 25400.0
  "mi" => 0.0
  "mm" => 25.4
  "nm" => 25400000.0
  "pc" => 0.0
  "pm" => 25400000000.0
  "yd" => 0.03
]
Clone this wiki locally