We finally arrive to the section where we actually make use of the
API. We will implement the fetchTwits
method in order to get a list of the last N number of tweets for a
given user. In order to perform requests, we need to add the
Authorization
header to each one, this
time with the access token. Since we want to make this class as
reusable as possible, let's extract this to a private method:
private function getAccessTokenHeaders(): array { if (empty($this->accessToken)) { $this->requestAccessToken(); } return ['Authorization' => 'Bearer ' . $this->accessToken]; }
As you can see, the preceding method also allows us to fetch the access token from the provider. This is useful, since if we make more than one request, we will just request the access token once, and we have one unique place to do so. Add now the following method implementation:
const GET_TWITS = '/1.1/statuses/user_timeline.json';
//...
public function fetchTwits(string $name, int $count): array {
$options = [
'headers' => $this->getAccessTokenHeaders(),
'query' => [
'count' => $count,
'screen_name' => $name
]
];
$response = $this->client->get(self::GET_TWITS, $options);
$responseTwits = json_decode($response->getBody(), true);
$twits = [];
foreach ($responseTwits as $twit) {
$twits[] = [
'created_at' => $twit['created_at'],
'text' => $twit['text'],
'user' => $twit['user']['name']
];
}
return $twits;
}
The first part of the preceding method builds the options
array with the access token headers and the
query string arguments—in this case, with the number of tweets to
retrieve and the user. We perform the GET request and decode the
JSON response into an array. This array contains a lot of
information that we might not need, so we iterate it in order to
extract those fields that we really want—in this example, the date,
the text, and the user.
In order to test the application, just invoke
the fetchTwits
method at the end of the
app.php
file, specifying the Twitter ID
of one of the people you are following, or yourself.
$twits = $twitter->fetchTwits('neiltyson', 10); var_dump($twits);
You should get a response similar to ours, shown in the following screenshot:

One thing to keep in mind is that access tokens expire after some time, returning an HTTP response with a 4xx status code (usually, 401 unauthorized). Guzzle throws an exception when the status code is either 4xx or 5xx, so it is easy manage these scenarios. You could add this code when performing the GET request:
try {
$response = $this->client->get(self::GET_TWITS, $options);
} catch (ClientException $e) {
if ($e->getCode() == 401) {
$this->requestAccessToken();
$response = $this->client->get(self::GET_TWITS, $options);
} else {
throw $e;
}
}