How to configure Symfony’s Service Container to use Twitter API


Keeping on with the series about Symfony’s Services container (another posts here and here), now we will use the service container to use Twitter API from a service.

To use Twitter API we need to handle http requests. I’ve written several post about http request with PHP (example1, example2), but today we will use one amazing library to build clients: Guzzle. Guzzle is amazing. We can easily build a Twitter client with it. There’s one example is its landing page:

<?php
$client = new Client('https://api.twitter.com/{version}', array('version' => '1.1'));
$oauth  = new OauthPlugin(array(
    'consumer_key'    => '***',
    'consumer_secret' => '***',
    'token'           => '***',
    'token_secret'    => '***'
));
$client->addSubscriber($oauth);

echo $client->get('/statuses/user_timeline.json')->send()->getBody();

If we are working within a Symfony2 application or a PHP application that uses the Symfony’s Dependency injection container component you can easily integrate this simple script in the service container. I will show you the way that I use to do it. Let’s start:

The idea is simple. First we include guzzle within our composer.json and execute composer update:

    "require": {
        "guzzle/guzzle":"dev-master"
    }

Then we will create two files, one to store our Twitter credentials and another one to configure the service container:

# twitter.conf.yml
parameters:
  twitter.baseurl: https://api.twitter.com/1.1

  twitter.config:
    consumer_key: ***
    consumer_secret: ***
    token: ***
    token_secret: ***
# twitter.yml
parameters:
  class.guzzle.response: Guzzle\Http\Message\Response
  class.guzzle.client: Guzzle\Http\Client
  class.guzzle.oauthplugin: Guzzle\Plugin\Oauth\OauthPlugin

services:
  guzzle.twitter.client:
    class: %class.guzzle.client%
    arguments: [%twitter.baseurl%]
    calls:
      - [addSubscriber, [@guzzle.twitter.oauthplugin]]

  guzzle.twitter.oauthplugin:
    class: %class.guzzle.oauthplugin%
    arguments: [%twitter.config%]

And finally we include those files in our services.yml:

# services.yml
imports:
- { resource: twitter.conf.yml }
- { resource: twitter.yml }

And that’s all. Now we can use the service without problems:

<?php

namespace Gonzalo123\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        $twitterClient = $this->container->get('guzzle.twitter.client');
        $status = $twitterClient->get('statuses/user_timeline.json')
             ->send()->getBody();

        return $this->render('AppBundle:Default:index.html.twig', array(
            'status' => $status
        ));
    }
}
Advertisement

8 thoughts on “How to configure Symfony’s Service Container to use Twitter API

  1. Gonzalo, although the “flat php” version works fine, the Symfony version doesn’t work for me( Symfony 2.2).

    It seems like passing the api version in baseurl on container is worth. The error:

    Client error response
    [status code] 404
    [reason phrase] Not Found
    [url] https://api.twitter.com/statuses/user_timeline.json

    The parameters after “/” dissapear. I tried pass the version api on container also and doesn’t work.

    1. Ok, after read the documentation I found the mistake. A “/” at the begining of statuses $twitterClient->get(‘/statuses/user_timeline.json’)

      1. Cool!. This sunday was marked in my personal ToDoList to check the issue and it’s solved before start!. I thought the problem was related to the changes that Twitter has been doing this days in its api (it was a nighmare in another proyect)

  2. I am traying to create a real time Symfony app using Ratchet library and I have already integrate ratchet in my symfony app but I have no idea how to start working with it I can’t find any tutorial or a small example about it. plz I nead you re help and that will be great if I can have just a small example to know how shoud I work with it

  3. Symfony2 show me two errors.

    InvalidArgumentException: There is no extension able to load the configuration for “twitter.config”. Looked for namespace “twitter.config”, found none

    FileLoaderLoadException: Cannot import resource from “services.yml”. (There is no extension able to load the configuration for “twitter.config”. Looked for namespace “twitter.config”, found none)

    1. That’s look like your yml file isn’t correct. You’re writing twitter.config at the same level of indentation than “parameters” (you missed the spaces before). “twitter.config” is a child of parameters. Symfony thinks that you’re trying to use a custom extension called “twitter.config” and it throws an error because it cannot find the extension.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.