未定义属性:GuzzleHttp \ Psr7 \ Response :: $ Results - Laravel 5.2使用API​​

时间:2016-05-16 00:29:34

标签: php laravel caching laravel-5.2

我正试图在我的Laravel 5 API中实现缓存,但我遇到了麻烦。我现在收到这个错误:

  

MedalController.php第19行中的ErrorException:
  未定义属性:GuzzleHttp \ Psr7 \ Response :: $ Results

任何人都可以弄清楚为什么这不是我的标题? 我之前从未真正使用过缓存,所以我可能在这里遗漏了一些东西

这就是我在Halo 5游戏中为每个玩家打电话并获得奖牌的方式:

GetDataController:

class GetDataController extends Controller {


    /**
     * Fetch a Players Arena Stats
     *
     * @param $gamertag
     * @return mixed
     */
    public function getPlayerArenaStats($gamertag) {

        $client = new GuzzleHttp\Client();

        $baseURL = 'https://www.haloapi.com/stats/h5/servicerecords/arena?players=' . $gamertag;

        $res = $client->request('GET', $baseURL, [
            'headers' => [
                'Ocp-Apim-Subscription-Key' => env('Ocp-Apim-Subscription-Key')
            ]
        ]);

        Cache::put('stats', $res, 10);

        if ($res->getStatusCode() == 200) {
            return $result = json_decode($res->getBody());
        } elseif ($res->getStatusCode() == 404) {
            return $result = redirect()->route('/');
        }

        return $res;
    }

}

我的MedalControler调用标题并尝试获取玩家的所有奖牌:

class MedalController extends Controller {

    /**
     * Get a Players Arena Medals
     *
     * @param $playerArenaMedalStats
     * @return mixed
     */
    public function getArenaMedals($playerArenaMedalStats) {


        $results = collect($playerArenaMedalStats->Results[0]->Result->ArenaStats->MedalAwards);

        $array = $results->sortByDesc('Count')->map(function ($item, $key) {
            return [
                'MedalId' => $item->MedalId,
                'Count' => $item->Count,
            ];
        });

        return $array;
    }


}

这就是获取,解码和返回奖牌的方式:

class StatsController extends Controller {


    /**
     * Return all Stats for a particular player
     * 
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {

        if (Cache::has('stats')) {
            $playerArenaMedalStats = Cache::get('stats');
            $playerArenaMedalStatsArray = app('App\Http\Controllers\MedalController')->getArenaMedals($playerArenaMedalStats);
            $arenaMedals = json_decode($playerArenaMedalStatsArray, true);
        } else {
            app('App\Http\Controllers\GetData\GetDataController')->getPlayerArenaStats($gamertag);
        }

      // More stuff here, shortened for simplicicty

      return view('player.stats')->with('arenaMedals', $arenaMedals);

    }


}

2 个答案:

答案 0 :(得分:0)

return $res方法结束时getPlayerArenaStats。它返回GuzzleHttp\Psr7\Response,您试图通过$playerArenaMedalStats->Results[0]上的getArenaMedals方法获取MedalController

答案 1 :(得分:0)

正如Ravisha Hesh所说,我只需要将getPlayerArenaStats中的缓存更改为:

 Cache::put('stats', json_decode($res->getBody()), 10);

我必须首先对它进行json_decode