课堂上的多种货币请求

时间:2016-05-31 08:09:50

标签: php

我有一个班级,用于提取当前USD/EUR种货币的信息。我想添加更多内容,例如AUD/EURCAD/EUR等,然后通过下拉菜单,用户可以选择要查看的内容。到目前为止,这是班级

class API
{
    public static function getUSDRate() {
        $urldata = get_curl_content('https://example.com/');
        $rates = json_decode($urldata, TRUE);        
        if (!$rates) {
            return '-';
        }

        $usdRate = @$rates['USD']['sell'];
        if (!$usdRate) {        
            return '-';
        }        
        return $usdRate;
    }

    public static function convertUSDToEUR($usdPrice) {
        $usdRate = self::getUSDRate();
        if ($usdRate === '-') {
            return '-';
    }

    $usdRate = doubleval($usdRate);
    return round($usdPrice / $usdRate, 8);
 }

所以我想添加例如

 $audRate = @$rates['AUD']['sell'];
 if (!$audRate) {        
      return '-';
 }        
 return $audRate;

 public static function convertAUDToEUR($audPrice) {
     $audRate = self::getAUDRate();
     if ($audRate === '-') {
         return '-';
 }

 $audRate = doubleval($audRate);
 return round($audPrice / $audRate, 8);

我需要为每个添加货币写这个吗?还是有更“智能”的方式?或者我必须为每种货币创建课程?

2 个答案:

答案 0 :(得分:1)

这是一个支持从任何货币转换的类的想法。您必须在创建类的实例时提供货币,然后您可以使用该对象的方法进行转换。

与你的代码一样,汇率是在静态变量中读取的,只有在以前没有完成时才会读取:

class CurrencyRate {
    public static $rates;
    private $conversionRate;
    private $currency;
    private $amount;

    function __construct($currFrom = "EUR") {
        // Currency to be provided when creating instance. EUR is default.
        if (empty(static::$rates)) {
            // Only request rates when not already loaded
            $urldata = get_curl_content('https://example.com/');
            self::$rates = json_decode($urldata, TRUE);
            // Add dummy rate for converting EUR to EUR
            self::$rates['EUR'] = ['sell' => '1'];
        }
        $this->currency = $currFrom;
        // Get exchange rate to EUR for this currency
        if (isset(self::$rates[$currFrom]['sell'])) {
            $this->conversionRate = doubleval(self::$rates[$currFrom]['sell']);
        } else {
            $this->conversionRate = 0; // not found
        }
    }

    public function currency() {
        return $this->currency;
    }

    public function rate() {
        return $this->conversionRate;
    }

    public function amount($newAmount = null) {
        // If argument is provided then this is a setter, otherwise a getter
        if (isset($newAmount)) {
            $this->amount = $newAmount;
            return $this; // allow "chaining"
        }
        return $this->amount;
    }

    public function euro() {
        // Convert object's amount to EUR 
        if ($this->conversionRate == 0) return "-"; // cannot convert
        return round($this->amount / $this->conversionRate, 8);
    }
}

使用示例:

// define the currency of your object. 
// You could pass 'AUD' or any other supported currency
$usd = new CurrencyRate('USD');

// set amount  in that currency
$usd->amount(12.34);

// get amount in that currency (is the same)
echo "amount: " . $usd->amount() . " USD<br>";

// get rate from that currency to EUR
echo "rate: " . $usd->rate() . "<br>";

// get amount in EUR
echo "Converted: " . $usd->euro() . " EUR<br>";

答案 1 :(得分:1)

如果您从服务中获得所有货币,我可以建议:

    <?php
    class API
    {
        // caching rates service results
        protected $ratesCache;

        // requesting rates service 
        // (we can force API request again by passing true)
        public function getRates($cacheClear = false) {
            // if we don't need to clear the cache and we already 
            // did request to rate service
            if ($cacheClear != true && !empty($this->ratesCache)) {
                // returning cached result
                return $this->ratesCache;
            }

            // request to rate service
            $urldata = get_curl_content('https://example.com/');
            $rates = json_decode($urldata, TRUE);        
            if (empty($rates)) {
                return '-';
            }

            // caching result
            $this->ratesCache = $rates;

            return $this->ratesCache;
        }

        // return the list of available rates
        public function getRatesList() {
            $rates = $this->getRates();
            // you can add here foreach to check which rates has 'sell' value
            // so you list only possible to convert currencies
            return array_keys($rates);
        }

        // convert currencies value to EUR
        public function convertToEUR($currency, $price) {
            $rates = $this->getRates();
            if (empty($rates[$currency]['sell'])) {
                return '-';
            }

            $rate = doubleval($rates[$currency]);
            return round($price / $rate, 8);
        }
     }

,用法如下:

<?php
$rateConvertor = new Api();
$availableRates = $rateConvertor->getRates();
// using foreach you can build <select> with currencies
// ...
// user select currency, set price (or you get it from somewhere else)
$amount = $rateConvertor->convertToEUR($currency, $price);