PHP code example of sprain / currency-converter

1. Go to this page and download the library: Download sprain/currency-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/ */

    

sprain / currency-converter example snippets




eate an instance
$converter = new \Sprain\CurrencyConverter\CurrencyConverter();

// Optional, but recommended: add a cache which will be used by some of the providers.
// You can use any cache system supported by Doctrine Cache.
$cache = new \Doctrine\Common\Cache\FilesystemCache(sys_get_temp_dir());
$converter->setCache($cache);

// Add at least one provider with its dependencies
$browser = new Buzz\Browser();
$converter->addProvider(new \Sprain\CurrencyConverter\Provider\FixerIoProvider($browser));

// Optional: Add more providers. The converter will then loop over the providers until
// a result is found. Use the second parameter to define the provider's priority.
// Higher values mean higher priority. The highest priority provider will be checked before all others.
$converter->addProvider(new \Sprain\CurrencyConverter\Provider\SwissGovernmentProvider($browser), 255);

// Do a quick conversion
$convertedAmount = $converter->convert(100)->from('USD')->to('EUR')->quick();

// Or alternatively, get a conversion object which contains more data
$conversion = $converter->convert(100)->from('USD')->to('EUR')->getConversion();
$convertedAmount    = $conversion->getAmountInTargetCurrency();
$exchangeRate       = $conversion->getExchangeRate();
$successfulProvider = $conversion->getProvider();



namespace Acme\Your\Project;

use Sprain\CurrencyConverter\Provider\Abstracts\AbstractProvider;

// Simply extend the AbstractProvider which comes with SprainCurrencyConverter
class MyCustomProvider extends AbstractProvider
{
    public function doGetExchangeRate()
    {
    	$baseCurrency   = $this->getBaseCurrency();
    	$targetCurrency = $this->getTargetCurrency();

    	// do your thing and return the exchange rate which represents the
    	// value of 1 unit of the base currency in units of the target currency.
    	// ...

        return $exchangeRate;
    }

	// Return your provider's name.
    public function getName()
    {
        return 'My custom provider';
    }

	// Optional:
	// Add this method and return an array of supported currencies.
	// The provider will only be used if either base currency _or_ target currency
	// is a member of this array.
    public function getSupportedCurrencies()
    {
        return array('USD', 'EUR');
    }
}



namespace Acme\Your\Project;

use Sprain\CurrencyConverter\Provider\Abstracts\AbstractCacheableProvider;

class MyCacheableCustomProvider extends AbstractCacheableProvider
{
	...	same, same as above
}