簡體   English   中英

如何改善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'];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM