PHP code example of pointybeard / laravel-unit-converter

1. Go to this page and download the library: Download pointybeard/laravel-unit-converter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pointybeard / laravel-unit-converter example snippets




use pointybeard\LaravelUnitConverter\Facades\UnitConverter;

// 25 Celsius to Fahrenheit
$result = UnitConverter::convert(25)->from('c')->to('f');
echo $result; // 77

// 2.5 Kilograms to Pounds
$result = UnitConverter::convert(2.5)->from('kg')->to('lb');
echo $result; // 5.51156

// 1,000 Millimeters to Meters
$result = UnitConverter::convert(1000)->from('mm')->to('m');
echo $result; // 1




use pointybeard\LaravelUnitConverter\Facades\UnitConverter;

try {
    UnitConverter::convert(10)->from('abc')->to('xyz');
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage(); 
    // Unsupported unit: abc
}




use Pointybeard\LaravelUnitConverter\UnitConverter;
use Pointybeard\LaravelUnitConverter\Calculators\CalculatorInterface;

class CustomCalculator implements CalculatorInterface
{
    protected function getConversions(): array
        return [
            'custom1' => [
                'custom2' => 2.0, // Conversion factor: 1 custom1 = 2 custom2
            ],
        ];
    }
}

// Register the custom calculator
UnitConverter::registerCalculator(new CustomCalculator);

// Usage
echo UnitConverter::convert(10)->from('custom1')->to('custom2'); // 20



use Pointybeard\LaravelUnitConverter\Calculators\AbstractCalculator;
use Pointybeard\LaravelUnitConverter\UnitConverter;

class CustomCalculator extends AbstractCalculator
{
    protected function getConversions(): array
    {
        return [
            'custom1' => [
                'custom2' => 'customMethod',
            ],
        ];
    }

    private function customMethod(float $value): float
    {
        return $value * 45;
    }
}

// Register the CustomCalculator
UnitConverter::registerCalculator(CustomCalculator::class);

// Usage
echo UnitConverter::convert(10)->from('custom1')->to('custom2'); // 450