Skip to content
This repository has been archived by the owner on Oct 14, 2023. It is now read-only.

Caching of currency conversion rates #2

Open
onlime opened this issue Jun 9, 2021 · 3 comments
Open

Caching of currency conversion rates #2

onlime opened this issue Jun 9, 2021 · 3 comments

Comments

@onlime
Copy link

onlime commented Jun 9, 2021

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

@amrshawky
Copy link
Owner

amrshawky commented Jun 27, 2021

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.

@DevNack
Copy link

DevNack commented Aug 25, 2021

Hey everybody, i think you shouldn't because rates may change every minute.

Best

@Shudhanshupatidar
Copy link

hey there, I think the rates are not valid. I'm converting USD to ETH and the ETH rates too much

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants