Caching of currency conversion rates
Hey @amrshawky, great project! This is just the easiest to use and cleanest currency library I found.
Are you planning to implement any kind of caching, so that we don't hit rate limits at exchangerate.host API? I would like to use the default Laravel Cache driver for this, maybe allowing to pass any PSR-6 compliant cache implementation. Caching should ideally be done on both single currency conversions (by e.g. storing from-to currency rates in an array) or for whole rates data (see below).
I didn't find it easy to implement this in your library and pass some caching over to amrshawky/currency through Laravel facade, so for the moment, I am just using this helper class in my project:
<?php
namespace App\Helpers;
use AmrShawky\LaravelCurrency\Facade\Currency;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class CurrencyCached
{
/**
* @var array currency rates
*/
protected array $rates;
/**
* @var string cache key
*/
protected string $cacheKey = 'currency-rates';
/**
* @param int|null $cacheTtl
*/
public function __construct(int $cacheTtl = null)
{
$ttl = $cacheTtl ?? config('app.cache_ttl.currency');
$this->rates = Cache::remember($this->cacheKey, $ttl, function () {
return Currency::rates()->latest()->get();
});
}
/**
* Currency conversion.
*
* @param float $amount
* @param string $toCurrency
* @param string $fromCurrency
* @return float|int
*/
public function convert(float $amount, string $toCurrency = 'CHF', string $fromCurrency = 'EUR')
{
return $amount * $this->rates[$toCurrency] / $this->rates[$fromCurrency];
}
}
Cheers, Philip
Hi @onlime,
Thanks for bringing this up, I didn't consider implementing any kind of caching to be honest since it's easy to use it with Laravel cache, But this would be a great feature to add to the library and I'll definitely consider adding it soon.
Thanks.
Hey everybody, i think you shouldn't because rates may change every minute.
Best
hey there, I think the rates are not valid. I'm converting USD to ETH and the ETH rates too much