Search code examples
phplaraveltwitterlaravel-5laravel-5.3

The right place to make calls to an API from Laravel


I have a view in Laravel that is responsible for displaying different data that are received from different calls to the Twitter API. This is the code:

TwitterRepository:

 public function getTwitterList($type, $count)
    {
        list($user, $settings) = $this->twitterConfig();

        $url = 'https://api.twitter.com/1.1/'.$type.'/list.json';
        $getfield = '?screen_name=' . $user . '&count=' . $count;
        $requestMethod = 'GET';
        $twitter = new TwitterAPIExchange($settings);
        $follow_count = $twitter->setGetfield($getfield)
            ->buildOauth($url, $requestMethod)
            ->performRequest();

        $get_count = json_decode($follow_count, true);

        return $get_count;
    }
... // Some similar methods

TwitterController:

public function index()
    {
        $twitterConfig = $this->twitterRepository->getTwitterData();

        $twitterFollowers = $twitterConfig['followers_count'];
        $twitterFollowing = $twitterConfig['friends_count'];
        $twitterCountTweet = $twitterConfig['statuses_count'];
        $twitterProfileDescription = $twitterConfig['description'];
        $twitterProfileImage = $twitterConfig['followers_count'];

        $lastTweets = $this->twitterRepository->getLastTweets();

        $twitterFollowingJson = $this->twitterRepository->getTwitterList('friends', 15);
        $twitterFollowingList = $twitterFollowingJson['users'];

        $twitterFollowersJson = $this->twitterRepository->getTwitterList('followers', 15);
        $twitterFollowersList = $twitterFollowersJson['users'];

        return view('admin.twitter-index', compact('twitterFollowers', 'twitterFollowing', 'twitterCountTweet',
            'twitterProfileDescription', 'twitterProfileImage', 'lastTweets', 'twitterFollowingList', 'twitterFollowersList'));
    }

The problem is that for every call I add to get other information in the same view (like lists of people), logically increases the response time of the page more and more. Could you help me improve this?

Many thanks.


Solution

  • The only real way reduce response time for the user here is to make the API calls asynchronously from the browser, rather than having your server make them.

    Consider building your view so that when it loads it shows "loading feedback" to the user and then makes the API calls via AJAX with each section showing content as each API call completes.