Error getting theme layout

Easy Way to Transform a Twitter OAuth Library into a Symfony 2 Bundle

Posted @ 4:04 pm by Milena Pavlova | Category: Technology | 0 Comments

I had to implement Twitter OAuth for a project built with Symfony 2. The framework itself made this task very easy to accomplish and I want to share my experience. Here is the step-by-step process:

1. Create a bundle. For more information, please visit this piece on creating pages in Symfony 2. For our example, let’s assume that we have run the following command:

2. Pick up a Twitter OAuth library. A list of Twitter REST API v1-capable libraries can be found here. I decided to work with TwitterOAuth, a Twitter API library by Abraham Williams. It has nice documentation and covers wide aspects of Twitter API.

3. Symfony 2 uses namespaces and the library has to be modified to comply with it. All classes should be separated in their own files. More on PHP Namespaces is available here. Let’s copy the API classes under ~/src/Solutionset/TwitterBundle/Api folder. The structure might be similar to this:

4. TwitterApi.php is the class where all the custom logic and integration with the Twitter API class happens. Let’s say that we need to implement a service that looks up Twitter users and returns back some information about them (http://api.twitter.com/1/users/lookup.json?screen_name={screen_name}).  Here is a basic class that does that:

5. Let’s add your Twitter OAuth credentials in ~/app/config/config.yml

parameters:
    # Twitter API
    twitter_api.key: aAbBcC123456....
    twitter_api.key_secret: ABCDFG123456....
    twitter_api.oauth_token: 123fFgG....
    twitter_api.oauth_token_secret: RrYy123456....

6. Now we can change ~/Solutionset/TwitterBundle/Resources/config/services.yml and register your TwitterApi.php as a service.

7. All of your controllers can access the new service and you can call it in a similar way:

The result should be a Json object with additional details about the specified users.

Happy coding!

Leave a reply

Error getting theme layout