【问题标题】:Class with single call to an api resource单次调用 api 资源的类
【发布时间】:2014-09-15 13:29:49
【问题描述】:

我有一个类,它有一个对 api 资源的方法调用,以及使用 api 调用方法输出的其他方法。就像现在一样,每次其他方法调用 api 方法时,api 方法都会一遍又一遍地向 api 发出请求。对 api 进行一次调用然后通过我的类使用输出的最佳方法是什么?见例子。

class foo {

    $param1;
    $param2;

    function getApi {

        return 'call_to_api' . $this->param1 . $this->$param2;
    }

    function do_stuff_1 {

        return 'do_some_other_stuff . '$this->getApi() . $param1
    }

    function do_stuff_2 {

        return 'do_some_other_other_stuff . '$this->getApi() . $param2
    }
}

【问题讨论】:

  • 你想要达到什么并不明显,各种方法是否以不同的参数调用外部api?或者每种方法的外部 api 的结果是否相同?如果是后者,只需将 api 调用的结果保存到一个私有类变量中,并在其他方法中使用它

标签: php class oop laravel dependency-injection


【解决方案1】:

您可以在对 API 的请求中使用 Laravel Cache

$url = 'http://api.url.com?data1=x&data2=y';

if (Cache::has($url)) 
{
    $apiResult = Cache::get($url);
}
else
{
    $apiResult = $this->apiGetResult($url);

    Cache::put($url, $apiResult, 5); // cache for 5 minutes
}

return $apiResult;

因此,您的 API 只有在之前从未被命中或缓存过期时才会被命中。使用 Laravel 缓存的好处是它可以在请求之间工作,因此如果您的应用程序在下一个请求中需要相同的数据,它将不会再次访问 API。

【讨论】:

    【解决方案2】:

    只有在参数被修改后,您才可以通过再次调用 API 来创建某种缓存:

      class foo {
    
        $param1;
        $param2;
        private $resultAPI = '';
        private $paramModified = false;
    
        function getApi {
          if ($this->resultAPI == '' || $this->paramModified) {
            $this->resultAPI = 'call_to_api' . $this->param1 . $this->$param2;
            $this->paramModified = false; 
          } 
          return $this->resultAPI;
        }
    
        function setParamX($val) {
          if ($this->paramX != $val) {
            $this->paramX = $val;
            $this->paramModified = true;
          }
        }
    
        function do_stuff_1 {
    
            return 'do_some_other_stuff . '$this->resultAPI . $param1
        }
    
        function do_stuff_2 {
    
            return 'do_some_other_other_stuff . '$this->resultAPI . $param2
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多