Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用对api资源的单个调用初始化_Php_Class_Oop_Laravel_Dependency Injection - Fatal编程技术网

Php 使用对api资源的单个调用初始化

Php 使用对api资源的单个调用初始化,php,class,oop,laravel,dependency-injection,Php,Class,Oop,Laravel,Dependency Injection,我有一个类,它具有对api资源的方法调用,以及使用api调用方法输出的其他方法。就像现在一样,每次其他方法调用api方法时,api方法都会一次又一次地向api发出请求。对api进行一次调用,然后通过类使用输出的最佳方法是什么?参见示例 class foo { $param1; $param2; function getApi { return 'call_to_api' . $this->param1 . $this->$param2;

我有一个类,它具有对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来创建某种缓存:

  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
    }
  }
您可以在对API的请求中使用:

$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或缓存过期时,才会命中API。使用Laravel缓存的好处在于,它可以在请求之间工作,因此,如果您的应用程序在下一个请求中需要相同的数据,它将不会再次命中API。

您想要实现的目标并不明显,不同的方法是否使用不同的参数调用外部API?或者每个方法的外部api结果是否相同?如果是后者,只需将api调用的结果保存到私有类变量,并在其他方法中使用