从Laravel调用API的正确位置

时间:2017-01-20 10:00:32

标签: php laravel twitter laravel-5 laravel-5.3

我在Laravel中有一个视图,负责显示从对Twitter API的不同调用接收的不同数据。这是代码:

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'));
    }

问题在于,为了在同一视图中添加其他信息(例如人员列表),我添加的每个调用都会越来越多地逻辑上增加页面的响应时间。你能帮我改进一下吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

减少用户响应时间的唯一方法是从浏览器异步进行API调用,而不是让服务器进行调用。

考虑构建视图,以便在加载时向用户显示“加载反馈”,然后通过AJAX进行API调用,每个部分在每个API调用完成时显示内容。