Previous Next

Zend_Service_Twitter

Introduction

Zend_Service_Twitter provides a client for the » Twitter REST API. Zend_Service_Twitter will allow you to query the public timeline and if you provide a username and password for Twitter it will allow you to get and update your status, reply to friends, direct message friends, mark tweets as favorite and much more.

Zend_Service_Twitter is implementing a REST service and all methods return an instance of Zend_Rest_Client_Result.

Zend_Service_Twitter is broken up into subsections so you can easily identify which type of call is being requested.

  • account, make sure that your account credentials are valid, check your api rate limit and end the current session for the authenticated user.

  • status, retrieves the public and user timelines and allows you to show, update, destroy and retrieve replies for the authenticated user.

  • user, retrieves the friends, followers for the authenticated user. With the show method you can return extended information about the passed in user.

  • directMessage, retrieves the authenticated users received direct message and allows you to send and delete new direct message.

  • friendship, create or remove a friendship for the authenticated user.

  • favorite, list, create or remove a favorite tweet.

Authentication

With the exception of fetching the public timeline Zend_Service_Twitter requires authentication to work. Twitter currently uses » HTTP Basic Authentication. You can pass in your username or registered email along with your password for twitter to login.

Example #1 Creating the Twitter Class

The following code sample is how you create the Twitter Service and pass in your username and password and then verify that they are correct.

$twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
// verify your credentials with twitter
$response = $twitter->account->verifyCredentials();

Account Methods

  • verifyCredentials, Use this method to test if supplied user credentials are valid with minimal overhead.

    Example #2 Verifying credentials

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->account->verifyCredentials();
  • endSession, Use this method to sign users out of client-facing applications.

    Example #3 Sessions ending

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->account->endSession();
  • rateLimitStatus, Returns the remaining number of API requests available to the authenticating user before the API limit is reached for the current hour.

    Example #4 Rating limit status

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->account->rateLimitStatus();

Status Methods

  • publicTimeline, Returns the 20 most recent statuses from non-protected users with a custom user icon. The public timeline is cached by twitter for 60 seconds.

    Example #5 Retrieving public timeline

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->status->publicTimeline();
  • friendsTimeline, Returns the 20 most recent statuses posted by the authenticating user and that user's friends.

    Example #6 Retrieving friends timeline

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->status->friendsTimeline();

    The friendsTimeline method accepts an array of optional parameters to modify the query.

    • since, Narrows the returned results to just those statuses created after the specified date/time (up to 24 hours old).

    • page, Which page you want to return.

  • userTimeline, Returns the 20 most recent statuses posted from the authenticating user.

    Example #7 Retrieving user timeline

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->status->userTimeline();

    The userTimeline method accepts an array of optional parameters to modify the query.

    • id, Specifies the ID or screen name of the user for whom to return the friends_timeline.

    • since, Narrows the returned results to just those statuses created after the specified date/time (up to 24 hours old).

    • page, Which page you want to return.

    • count, Specifies the number of statuses to retrieve. May not be greater than 200.

  • show, Returns a single status, specified by the id parameter below. The status's author will be returned inline. This method required a tweet id to be passed in.

    Example #8 Showing user status

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->status->show(1234);
  • update, Updates the authenticating user's status. This method requires that you pass in the status update that you want to post to twitter. A second optional parameter is the id of the tweet that you are replying to.

    Example #9 Updating user status

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->status->update('My Great Tweet');

    The update method accepts a second additional parameter.

    • in_reply_to_status_id, The ID of an existing status that the status to be posted is in reply to.

  • replies, Returns the 20 most recent @replies (status updates prefixed with @username) for the authenticating user.

    Example #10 Showing user replies

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->status->replies();

    The replies method accepts an array of optional parameters to modify the query.

    • since, Narrows the returned results to just those statuses created after the specified date/time (up to 24 hours old).

    • page, Which page you want to return.

    • since_id, Returns only statuses with an ID greater than (that is, more recent than) the specified ID.

  • destroy, Destroys the status specified by the required ID parameter.

    Example #11 Deleting user status

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->status->destroy(12345);

User Methods

  • friends, Returns up to 100 of the authenticating user's friends who have most recently updated, each with current status inline.

    Example #12 Retrieving user friends

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->user->friends();

    The friends method accepts an array of optional parameters to modify the query.

    • id, Specifies the ID or screen name of the user for whom to return a list of friends.

    • since, Narrows the returned results to just those statuses created after the specified date/time (up to 24 hours old).

    • page, Which page you want to return.

  • followers, Returns the authenticating user's followers, each with current status inline.

    Example #13 Retrieving user followers

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->user->followers();

    The followers method accepts an array of optional parameters to modify the query.

    • id, Specifies the ID or screen name of the user for whom to return a list of followers.

    • page, Which page you want to return.

  • show, Returns extended information of a given user, specified by ID or screen name as per the required id parameter below

    Example #14 Showing user informations

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->user->show('myfriend');

Direct Message Methods

  • messages, Returns a list of the 20 most recent direct messages sent to the authenticating user.

    Example #15 Retrieving recent direct messages received

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->directMessage->messages();

    The message method accepts an array of optional parameters to modify the query.

    • since_id, Returns only direct messages with an ID greater than (that is, more recent than) the specified ID.

    • since, Narrows the returned results to just those statuses created after the specified date/time (up to 24 hours old).

    • page, Which page you want to return.

  • sent, Returns a list of the 20 most recent direct messages sent by the authenticating user.

    Example #16 Retrieving recent direct messages sent

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->directMessage->sent();

    The sent method accepts an array of optional parameters to modify the query.

    • since_id, Returns only direct messages with an ID greater than (that is, more recent than) the specified ID.

    • since, Narrows the returned results to just those statuses created after the specified date/time (up to 24 hours old).

    • page, Which page you want to return.

  • new, Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.

    Example #17 Sending direct message

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->directMessage->new('myfriend', 'mymessage');
  • destroy, Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.

    Example #18 Deleting direct message

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->directMessage->destroy(123548);

Friendship Methods

  • create, Befriends the user specified in the ID parameter as the authenticating user.

    Example #19 Creating friend

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->friendship->create('mynewfriend');
  • destroy, Discontinues friendship with the user specified in the ID parameter as the authenticating user.

    Example #20 Deleting friend

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->friendship->destroy('myoldfriend');
  • exists, Tests if a friendship exists between the authenticated user and the passed in user.

    Example #21 Checking friend existence

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->friendship->exists('myfriend');

Favorite Methods

  • favorites, Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter

    Example #22 Retrieving favorites

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->favorite->favorites();
    • id, The ID or screen name of the user for whom to request a list of favorite statuses.

    • page, Which page you want to return.

  • create, Favorites the status specified in the ID parameter as the authenticating user..

    Example #23 Creating favorites

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->favorite->create(12351);
  • destroy, Un-favorites the status specified in the ID parameter as the authenticating user.

    Example #24 Deleting favorites

    $twitter = new Zend_Service_Twitter('myusername', 'mysecretpassword');
    $response = $twitter->favorite->destroy(12351);

Zend_Service_Twitter_Search

Introduction

Zend_Service_Twitter_Search provides a client for the » Twitter Search API. The Twitter Search service is use to search Twitter. Currently it only returns data in Atom or JSON format but a full REST service is in the future which will support XML responses.

Twitter Trends

Returns the top ten queries that are currently trending on Twitter. The response includes the time of the request, the name of each trending topic, and the url to the Twitter Search results page for that topic. Currently the search API for trends only supports a JSON return so the function returns an array.

$twitter_search = new Zend_Service_Twitter_Search();
$twitter_trends = $twitter_search->trends();

foreach($twitter_trends as $trend) {
    print $trend['name'] . ' - ' . $trend['url'] . PHP_EOL
}

The return array has two values in it:

  • name, the name of trend.

  • url, the url to see the tweets for that trend.

Searching Twitter

Using the search method returns tweets that match a specific query. There are a number of » Search Operators that you can use to query with.

The search method can accept six different optional URL parameters passed in as an array:

  • lang, restricts the tweets to a given language, lang must be given by an » ISO 639-1 code.

  • rpp, the number of tweets to return per page, up to a max of 100.

  • page, the page number to return, up to a max of roughly 1500 results (based on rpp * page)

  • since_id, returns tweets with status ids greater than the given id.

  • show_user, when "true", adds ">user<:" to the beginning of the tweet. This is useful for readers that do not display Atom's author field. The default is "false"

  • geocode, returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile. The parameter value is specified by "latitude,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers).

Example #25 JSON Search Example

The following code sample will return an array with the values search results

$twitter_search = new Zend_Service_Twitter_Search('json');
$search_results = $twitter_search->search('zend', array('lang' => 'en'));

Example #26 ATOM Search Example

The following code sample will return a Zend_Feed_Atom object.

$twitter_search = new Zend_Service_Twitter_Search('atom');
$search_results = $twitter_search->search('zend', array('lang' => 'en'));

Zend-specific Accessor Methods

While the Twitter Search API only specifies two methods, Zend_Service_Twitter_Search has additional accessors that may be used for modifying internal properties.

  • getResponseType() and setResponseType() allow you to retrieve and modify the response type of the search between JSON and ATOM.

Previous Next
Introduction to Zend Framework
Présentation
Installation
Zend_Acl
Introduction
Affiner les Contrôles d'Accès
Utilisation avancée
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Théorie générale
Exemples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Authentification avec une table de base de données
Authentification "Digest"
Adaptateur d'authentification HTTP
LDAP Authentication
Authentification OpenID
Zend_Cache
Introduction
Aspect théorique
Les frontends Zend_Cache
Les backends Zend_Cache
Zend_Captcha
Introduction
Opération Captcha
Adaptateurs CAPTCHA
Zend_CodeGenerator
Introduction
Exemples Zend_CodeGenerator
Zend_CodeGenerator Réference
Zend_Config
Introduction
Aspect théorique
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Déclarer les règles Getopt
Extraire les options et les arguments
Configurer Zend_Console_Getopt
Zend_Controller
Zend_Controller - Démarrage rapide
Fondations de Zend_Controller
Le contrôleur frontal (Front Controller)
L'objet Requête
Routeur Standard
Le distributeur
Contrôleurs d'action
Aides d'action (Helper)
Objet de réponse
Plugins
Utilisation de conventions de dossiers modulaires
Exceptions avec MVC
Migrer depuis des versions précédentes
Zend_Currency
Introduction à Zend_Currency
How to Work with Currencies
Migrer depuis des versions antérieures
Zend_Date
Introduction
Aspect théorique
Méthodes de base
Zend_Date API Overview
Créer des dates
Constants for General Date Functions
Exemples concrets
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Relations Zend_Db_Table
Zend_Debug
Afficher des informations
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Les aides de vues Dojo
Les éléments de formulaire et les décorateurs Dojo
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Utiliser les exceptions
Zend_Feed
Introduction
Importer des flux
Obtenir des flux à partir de pages Web
Consommer un flux RSS
Consommer un flux Atom
Consommer une entrée Atom particulière
Modifier la structure du flux ou des entrées
Classes personnalisées pour les flux et entrées
Zend_File
Zend_File_Transfer
Validateurs pour Zend_File_Transfer
Filtres pour Zend_File_Transfer
Migrer à partir des versions précédentes
Zend_Filter
Introduction
Classes de filtre standards
Chaînes de filtrage
Écriture de filtres
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form démarrage rapide
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Créer un visuel personnalisé en utilisant Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Décorateurs standards fournis avec Zend Framework
Internationaliser un formulaire Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authentification par procédé AuthSub
Using the Book Search Data API
Authentification avec ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Utilisation des albums Web Picasa
Using the YouTube Data API
Attraper les exceptions Gdata
Zend_Http
Introduction
Zend_Http_Client - Utilisation avancée
Zend_Http_Client - Adaptateurs de connexion
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Utilisation de base
Utilisation avancée de Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout - Démarrage rapide
Zend_Layout options de configuration
Zend_Layout, utilisation avancée
Zend_Ldap
Introduction
Zend_Loader
Charger les fichiers et les classes dynamiquement
L'autoloader
Autoloaders de ressources
Chargeur de Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrer à partir des versions précédentes
Zend_Log
Présentation
Rédacteurs (Writers)
Formateurs (mise en forme)
Filtres
Zend_Mail
Introduction
Envoyer des émail en utilisant SMTP
Envoyer plusieurs émail par connexion SMTP
Utiliser différents transports
Émail HTML
Fichiers joints
Ajouter des destinataires
Contrôler les limites MIME
En-têtes additionnels
Jeux de caractères
Encodage
Authentification SMTP
Sécuriser les transports SMTP
Lire des émail
Zend_Measure
Introduction
Création d'une mesure
Récupérer des mesures
Manipuler des mesures
Types de mesures
Zend_Memory
Présentation
Manager de mémoire
Objet mémoire
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Utilisation
Configuration
Utilisation avancée
Zend_Pdf
Introduction
Créer et charger des documents PDF
Sauvegarder les changement dans un document PDF
Les pages d'un document
Dessiner
Informations du document et métadonnées
Exemple d'utilisation du module Zend_Pdf
Zend_ProgressBar
Zend_ProgressBar
Zend_Reflection
Introduction
Zend_Reflection Exemples
Réference de Zend_Reflection
Zend_Registry
Utiliser le registre
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Vue d'ensemble
Créer des index
Searching an Index
Query Language
Query Construction API
Jeu de caractères
Extensibility
Agir avec Lucene Java
Avancé
Bonnes pratiques
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Stroage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Usage basique
Utilisation avancée
Gestion générale de la session
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL
Auto découverte
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Utiliser Zend_TimeSync
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Zend_Tool_Project
Zend_Tool_Project Introduction
Create A Project
Zend Tool Project Providers
Zend_Translate
Introduction
Adaptateurs pour Zend_Translate
Utiliser les adaptateurs de traduction
Migrer à partir des versions précédentes
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Classes de validation standard
Chaînes de validation
Écrire des validateurs
Validation Messages
Zend_Version
Lire la version de Zend Framework
Zend_View
Introduction
Scripts de contrôleur
Scripts de vue
Aides de vue
Zend_View_Abstract
Migration depuis les versions précédentes
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Configuration système requise par Zend Framework
Introduction
Convention de codage PHP de Zend Framework
Vue d'ensemble
Formatage des fichiers PHP
Conventions de nommage
Style de codage
Zend Framework Performance Guide
Introduction
Chargement des classes
Zend_Db Performance
Internationalisation (i18n) and Localisation (l10n)
View Rendering
Informations de copyright