Best way to cache currency translation rates in CodeIgniter
My shopping app needs to do currency conversion, my plan is to use a cronta开发者_Go百科b to grab the latest exchange rates once an hour. My question is whats the best way to store and use this in my CI application. Should I: - Write it to the DB everytime its run and then grab the rate from the DB evrytime i need to do a conversion - Do the same but with a text file - Write it to a constant in the index.php - Some sort of core or hook file
Whats the most efficient way
The quick & dirty way would be writing a PHP file with the said currencies. You can use var_export()
to save them safely.
Config:
$file = '/path/to/currencies.php';
Cronjob:
// get data from API (note: you should use proper functions via CURL)
$currencies = file_get_contents('http://some.api.com/currencies');
// decode data
$currencies = json_decode( currencies );
// export data into PHP format
$currencies = var_export( currencies, true );
// save to file
file_put_contents($file, "<?php\r\n $currencies=".$currencies."; \r\n?>");
Currency Page:
// ensure you get a default something
$currencies = array();
// load data file (note, we use include so we can load it whenever we want)
@include $file;
// output something from array
echo $currencies['EUR'];
Note that we don't even connect to DB anywhere, making this very fast. There is also no parsing/conversion. With the DB concept, you have to at least loop over the database rows. Using a normal config medium, such as ini, json or xml files would requiring some form of parsing after PHP loads. Whereas, with this method, it is a part of PHP's loading process; you're just including a small PHP file.
I think the most common way (which is also efficient) is to have a currencies table in the database.
- Each currency & rate has its own row.
- Based on the chosen locale, grab the appropriate currency info from the database on each page request.
- Wrap your price displays in a function that performs the currency conversion (simple multiplication of the base currency).
精彩评论