简体   繁体   中英

Where and how to store currency rates?

I have written a script that gets paypals current rates compared with the dollar every hour (the currency my products are in by default).

The user can set their currency in their settings and that is store in the user table.

My initial idea was to store all the currencies rates in the database and then when the user logs in store the currency code and rate in their session. Then around each price I have a function that multiples the price by the users rate and appends the currency code on the end.

My only worry being is that the session variable may exist for sometime and could potentially make the price completely wrong.

Rather than store the rates in the session, should I just store their currency code and store the rates in a memory table or on the file system for fast access and have the price conversion function access it? So the prices are as up to date as the rates.

How is this normally achieved?

您是否可以用他们定价的货币显示价格,并显示用户所选货币的近似价格,但需要注意的是实际汇率可能会在结账时有所不同?

Just cache the calls that gets the Exchange Rates from PayPal. That's all there is to do. As long as the cache is not stale, your users will multiply with the cached values. If the cache goes stale, the new rate will be fetched, eg ( faux code )

$currency = 'usd';
if (!$cache->has("exRate-$currency")) {
    $exRate = ForEx::find($currency);
    $cache->save("exRate-$currency");
} else {
    $exRate = $cache->get("exRate-$currency");
}
CurrencyConverter::setRate($currency, $exRate);
CurrencyConverter::convert(100, 'eur', 'usd');

For caches use APC or memcached .

You can change the default lifetime of a session - it's stored in the php.ini variable session.gc_maxlifetime . The default is 1440 (24 hours), after which the session will be cleared up by the following garbage collection.

The variable can be edited directly (in the file) or with ini_set :

ini_set('session.gc_maxlifetime', 60); // set to 1 hour

Edit

You can increase the probability of the garbage collection running on any given call using the variables session.gc_probability and session.gc_divisor . Documentation is at http://www.php.net/manual/en/session.configuration.php

Lets do the Jeopardy thing.

Is it possible to use $_SERVER as a application-wide global object, similar to ASP's Application object? If not, is there a PHP application object?

If so, you could store the currency rate in $_SERVER, then update it when necessary (eg when Paypal updates it's currency rate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM