Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Easily work with the Twitter Streaming API in PHP

Original – by Freek Van der Herten – 3 minute read

Twitter provides a streaming API with which you can do interesting things such as listen for tweets that contain specific strings or actions a user might take (e.g. liking a tweet, following someone,...). In this post you'll learn an easy way to work with that API.

Phirehose

When researching on how to work with the streaming API in PHP it stumbled upon Phirehose. This package can authenticate and set up a connection with the streaming API. Unfortunately the API of Phirehose itself is a bit unwieldy. That's why I created a wrapper around Phirehose that makes setting up a connection to Twitter's streaming API a breeze. I made a framework agnostic version of the package and a Laravel specific one.

Getting started

Let's review how to integrate the package in a Laravel app. First you need to retrieve some credentials from Twitter. Fortunately this is very easy. Head over to the Application management on Twitter to create an application.

Once you've created your application, click on the Keys and access tokens tab to retrieve your consumer_key, consumer_secret, access_token and access_token_secret.

Now you've got the credentials let's install the package in a Laravel app.

Like a gazillion other packages laravel-twitter-streaming-api can be installed via composer.

composer require spatie/laravel-twitter-streaming-api

Next, install the service provider.

// config/app.php
'providers' => [
    ...
    Spatie\LaravelTwitterStreamingApi\TwitterStreamingApiServiceProvider::class,
];

If you love working with facades, you'll be happy to know that there's one provider by the package.

// config/app.php
'aliases' => [
    ...
    'TwitterStreamingApi' => Spatie\LaravelTwitterStreamingApi\TwitterStreamingApiFacade::class,
];

The config file must be published with this command:

php artisan vendor:publish --provider="Spatie\LaravelTwitterStreamingApi\TwitterStreamingApiServiceProvider" --tag="config"

It'll copy a file with this content in config/laravel-twitter-streaming-api.php

return [

    /**
     * To work with Twitter's Streaming API you'll need some credentials.
     *
     * If you don't have credentials yet, head over to https://apps.twitter.com/
     */

    'access_token' => env('TWITTER_ACCESS_TOKEN'),

    'access_token_secret' => env('TWITTER_ACCESS_TOKEN_SECRET'),

    'consumer_key' => env('TWITTER_CONSUMER_KEY'),

    'consumer_secret' => env('TWITTER_CONSUMER_SECRET'),
];

Create the TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET, TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET keys in your .env and set them to the values you retrieved on Twitter.

Now you're ready to use the package.

Your first stream

Let's listen for all tweets that contain the string #laravel. I've created an example Laravel app with the package preinstalled. This artisan command included to listen for incoming tweets:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use TwitterStreamingApi;

class ListenForHashTags extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'twitter:listen-for-hash-tags';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Listen for hashtags being used on Twitter';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        TwitterStreamingApi::publicStream()
            ->whenHears('#laravel', function (array $tweet) {
                dump("{$tweet['user']['screen_name']} tweeted {$tweet['text']}");
            })
            ->startListening();
    }
}

In case you haven't used it before, that dump function does the same as dd but without the dying part. The call to startListening() starts the listening process. The function will run forever so any code after that won't be executed.

Let's go ahead an execute the command. In the output you'll see some logging done by the underlying Phirehose package.

Now tweet something with #laravel in the tweet.

In the console you'll see your own tweet appearing immediately.

Pretty cool! Be aware that this API works in realtime, so they could report a lot of activity. If you need to do some heavy work processing that activity it's best to put that work in a queue to keep your listening process fast.

Another example

In the example above we've used the public stream. You can use that one to listen for tweets with specific strings posted on Twitter. But there also other kinds of streams. With the user stream you can listen for certain events that happen for the authenticated user.

Here's an example that demonstrates how you can listen people favouriting on of your tweets:

TwitterStreamingApi::userStream()
->onEvent(function(array $event) {
    if ($event['event'] === 'favorite') {
        echo "Our tweet {$event['target_object']['text']} got favourited by {$event['source']['screen_name']}";
    }
})
->startListening();

In closing

The Twitter Streaming API's are pretty powerful. If you want to know more about them take a look at the official docs. The easiest way to get started with them is by using our laravel specific or framework agnostic package. If you don't like wrappers and want to use Phirehose directly, then read this tutorial on Scotch.io.

In any case check out the other PHP and Laravel packages our team has made before.

Have fun building a cool app using Twitter's streaming APIs!

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "Easily work with the Twitter Streaming API in PHP"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.