PHP 在类中重用函数代码


PHP Reusing function code within a class

PHP - 在类中重用代码

我有一个PHP类来使用REST API。我有几种方法可以从 API 返回基本信息 - 但大多数数据来自单个 API 调用。

例如,假设我们引用一个 API 来获取汽车模型:

汽车原料药

http://cars.com/webservice/getCars.jsp?ALL

这个请求(不是真正的网络服务顺便说一句)将返回所有汽车。

假设我想列出所有配备 V6 发动机的汽车。假设这 iS 不是 API 的功能。

合乎逻辑的做法是检索所有汽车,根据条件进行过滤,然后返回我们正在寻找的内容。

现在。。。假设我们想要一堆关于汽车的不同细节——车轮、刹车、火花塞等。重复相同的代码来检索最初的汽车列表是没有意义的。

class Cars {
public function getCars() {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output; 
}
public function getCarEngines($type) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    //Get Engines from list of cars
    return $output['engines'][$type];
}   
}   

如何有效地复制我的代码,以便我可以提供其他方法,同时最大限度地减少代码行数?

首先,您可以将特定于 cURL 的功能移动到其自己的函数中,该函数可以重用,如下所示:

class Cars {
    public function getCars() {
        $output = $this->curlRequest($url);
        return $output; 
    }
    public function getCarEngines($type) {
        $output = $this->curlRequest($url);
        //Get Engines from list of cars
        return $output['engines'][$type];
    }   
    /**
     * Return the result of a cURL request.
     * @param  string $url
     * @return mixed
     */
    protected function curlRequest($url) 
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}   

根据您的数据结构,您可以更进一步,当您getCarEngines() 时,您将首先getCars(),然后过滤输出(如果适用),您可以执行以下操作:

public function getCars() {
    return $this->curlRequest($url); 
}
public function getCarEngines($type) {
    $output = $this->getCars();
    // Get Engines from list of cars
    return $output['engines'][$type];
}   

仅供参考 - 我忽略了这样一个事实,即 $url 变量在您的示例中未定义,并且您没有将任何数据与 cURL 请求一起传递。您需要在 curlRequest() 函数中添加一个 $data 变量,以便在需要时也能传递数据,并从某处获取$url(类属性?