如何改进PHP中的代码结构


How to improve code structure in PHP?

我在Laravel的控制器中创建了两个方法,使用PHP CURL从另一个网站获取数据并传递到视图。我将使用httpData方法来初始化IDURL,并使用getHttpCode法来获取HTTP_code以查找从其他网站获取数据时会发生的任何错误。但我不太了解下面的代码性能,以及如何在PHPstrom中测试以确保性能

这是我的功能

 private function httpData($url =null, $id = null)
    {
        if($id){
            $url = 'http://assignment.gae.golgek.mobi/api/v1/items/'.$id;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 30);
        curl_setopt($ch, CURLINFO_HTTP_CODE, true);
        curl_setopt($ch, CURLOPT_PRIVATE, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!$executed = curl_exec($ch)) {
            $res = $executed;
            $data = false;
            curl_close($ch);
        } else {
            if ($this->http_code = $this->getHttpCode(curl_getinfo($ch))) {
                $res = $this->http_code;
                $data = $executed;
            } else {
                $res = false;
            }
        }
        return ['s_respond' => $res, 'data' => $executed];
    }
    private function getHttpCode($http)
    {
        if (is_array($http)) {
            if (!empty($http['http_code'] || $http['http_code'] != 0)) {
                return $http['http_code'];
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

我将把这种方法称为

public function sendData()
{
    $url = 'website/api/v1/products';
    $data = $this->httpData($url);
    return view('products.list', ['data'=>$data]);
}

感谢的帮助

我建议您添加"早期返回模式"。

我在你的getHttpCode中做了一个重写,对我来说似乎更清楚:

private function getHttpCode($http)
{
    if ( !is_array($http) 
      || empty($http['http_code'])
      || $http['http_code'] === 0)
    {
        return false;
    }
    return $http['http_code'];
}