Previous Next

Using Google Base

The Google Base data API is designed to enable developers to do two things:

  • Query Google Base data to create applications and mashups.

  • Input and manage Google Base items programmatically.

There are two item feeds: snippets feed and customer items feeds. The snippets feed contains all Google Base data and is available to anyone to query against without a need for authentication. The customer items feed is a customer-specific subset of data and only a customer/owner can access this feed to insert, update, or delete their own data. Queries are constructed the same way against both types of feeds.

See » http://code.google.com/apis/base for more information about the Google Base API.

Connect To The Base Service

The Google Base API, like all GData APIs, is based off of the Atom Publishing Protocol (APP), an XML based format for managing web-based resources. Traffic between a client and the Google Base servers occurs over HTTP and allows for both authenticated and unauthenticated connections.

Before any transactions can occur, this connection needs to be made. Creating a connection to the base servers involves two steps: creating an HTTP client and binding a Zend_Gdata_Gbase service instance to that client.

Authentication

The Google Base API allows access to both public and private base feeds. Public feeds do not require authentication, but are read-only and offer reduced functionality. Private feeds offers the most complete functionality but requires an authenticated connection to the base servers. There are three authentication schemes that are supported by Google Base:

  • ClientAuth provides direct username/password authentication to the base servers. Since this scheme requires that users provide your application with their password, this authentication is only recommended when other authentication schemes are insufficient.

  • AuthSub allows authentication to the base servers via a Google proxy server. This provides the same level of convenience as ClientAuth but without the security risk, making this an ideal choice for web-based applications.

The Zend_Gdata library provides support for all three authentication schemes. The rest of this chapter will assume that you are familiar the authentication schemes available and how to create an appropriate authenticated connection. For more information, please see section Google Data Client Authentication. or the » Authentication Overview in the Google Data API Developer's Guide.

Create A Service Instance

In order to interact with Google Base, this library provides the Zend_Gdata_Gbase service class. This class provides a common interface to the Google Data and Atom Publishing Protocol models and assists in marshaling requests to and from the base servers.

Once deciding on an authentication scheme, the next step is to create an instance of Zend_Gdata_Gbase . This class takes in an instance of Zend_Http_Client as a single argument. This provides an interface for AuthSub and ClientAuth authentication, as both of these creation of a special authenticated HTTP client. If no arguments are provided, an unauthenticated instance of Zend_Http_Client will be automatically created.

The example below shows how to create a Base service class using ClientAuth authentication:



A Base service using AuthSub can be created in a similar, though slightly more lengthy fashion:

 Script execution begins here <-

// Make sure http://code.google.com/apis/gdata/reference.html#Queriesthat the user has a valid session, so we can record the
// AuthSub session token once it is available.
session_start();

// Create an instance of the Base service, redirecting the user
// to the AuthSub server if necessary.
$service = new Zend_Gdata_Gbase(getAuthSubHttpClient());

Finally, an unauthenticated server can be created for use with snippets feeds:



        

Retrieve Items

You can query customer items feed or snippets feed to retrieve items. It involves two steps, sending a query and iterating through the returned feed.

Send a Structured Query

You can send a structured query to retrieve items from your own customer items feed or from the public snippets feed.

When retrieveing items using the Base API, specially constructed query URLs are used to describe what events should be returned. The Zend_Gdata_Gbase_ItemQuery and Zend_Gdata_Gbase_SnippetQuery classes simplify this task by automatically constructing a query URL based on provided parameters.

Query Customer Items Feed

To execute a query against the customer items feed, invoke newItemQuery() and getGbaseItemFeed() methods:

newItemQuery();
$query->setBq('[title:Programming]');
$query->setOrderBy('modification_time');
$query->setSortOrder('descending');
$query->setMaxResults('5');
$feed = $service->getGbaseItemFeed($query);

A full list of these paremeters is available at the » Query parameters section of the Customer Items Feed documentation.

Query Snippets Feed

To execute a query against the public snippets feed, invoke newSnippetQuery() and getGbaseSnippetFeed() methods:

newSnippetQuery();
$query->setBq('[title:Programming]');
$query->setOrderBy('modification_time');
$query->setSortOrder('descending');
$query->setMaxResults('5');
$feed = $service->getGbaseSnippetFeed($query);

A full list of these paremeters is available at the » Query parameters section of the Snippets Feed documentation.

Iterate through the Items

Google Base items can contain item-specific attributes such as <g:main_ingredient> and <g:weight>.

To iterate through all attributes of a given item, invoke getGbaseAttributes() and iterate through the results:

entries as $entry) {
  // Get all attributes and print out the name and text value of each attribute
  $baseAttributes = $entry->getGbaseAttributes();
  foreach ($baseAttributes as $attr) {
    echo "Attribute " . $attr->name . " : " . $attr->text . "
"; } }

Or, you can look for specific attribute name and iterate through the results that match:

entries as $entry) {
  // Print all main ingredients 
  $baseAttributes = $entry->getGbaseAttribute("main_ingredient");
  foreach ($baseAttributes as $attr) {
    echo "Main ingredient: " . $attr->text . "
"; } }

Insert, Update, and Delete Customer Items

A customer/owner can access his own Customer Items feed to insert, update, or delete their items. These operations do not apply to the public snippets feed.

You can test a feed operation before it is actually executed by setting the dry-run flag ($dryRun) to true. Once you are sure that you want to submit the data, set it to false to execute the operation.

Insert an Item

Items can be added by using the insertGbaseItem() method for the Base service:

newItemEntry();

// Add title
$title = "PHP Developer Handbook";
$newEntry->title = $service->newTitle(trim($title));

// Add some content
$content = "Essential handbook for PHP developers.";
$newEntry->content = $service->newContent($content);
$newEntry->content->type = 'text';

// Define product type
$itemType = "Products";
$newEntry->itemType = $itemType;

// Add item specific attributes
$newEntry->addGbaseAttribute("product_type", "book", "text");
$newEntry->addGbaseAttribute("price", "12.99 USD", "floatUnit");
$newEntry->addGbaseAttribute("quantity", "10", "int");
$newEntry->addGbaseAttribute("weight", "2.2 lbs", "numberUnit");
$newEntry->addGbaseAttribute("condition", "New", "text");
$newEntry->addGbaseAttribute("author", "John Doe", "text");
$newEntry->addGbaseAttribute("edition", "First Edition", "text");
$newEntry->addGbaseAttribute("pages", "253", "number");
$newEntry->addGbaseAttribute("publisher", "My Press", "text");
$newEntry->addGbaseAttribute("year", "2007", "number");
$newEntry->addGbaseAttribute("payment_accepted", "Google Checkout", "text");

$dryRun = true;
$createdEntry = $service->insertGbaseItem($newEntry, $dryRun);

Modify an Item

You can update each attribute element of an item as you iterate through them:

title = $service->newTitle($newTitle);

// Find  attribute and update the price
$baseAttributes = $entry->getGbaseAttribute("price");
if (is_object($baseAttributes[0])) {
  $newPrice = "16.99 USD";
  $baseAttributes[0]->text = $newPrice;
}

// Find  attribute and update the number of pages
$baseAttributes = $entry->getGbaseAttribute("pages");
if (is_object($baseAttributes[0])) {
  $newPages = "278";
  $baseAttributes[0]->text = $newPages;

  // Update the attribute type from "number" to "int"
  if ($baseAttributes[0]->type == "number") {
    $newType = "int";
    $baseAttributes[0]->type = $newType;
  }
}

// Remove  attributes
$baseAttributes = $entry->getGbaseAttribute("label");
foreach ($baseAttributes as $note) {
  $entry->removeGbaseAttribute($note);
}

// Add new attributes
$entry->addGbaseAttribute("note", "PHP 5", "text");
$entry->addGbaseAttribute("note", "Web Programming", "text");

// Save the changes by invoking save() on the entry object itself
$dryRun = true;
$entry->save($dryRun);

// Or, save the changes by calling updateGbaseItem() on the service object
// $dryRun = true;
// $service->updateGbaseItem($entry, $dryRun);

After making the changes, either invoke save($dryRun) method on the Zend_Gdata_Gbase_ItemEntry object or call updateGbaseItem($entry, $dryRun) method on the Zend_Gdata_Gbase object to save the changes.

Delete an Item

You can remove an item by calling deleteGbaseItem() method:

deleteGbaseItem($entry, $dryRun);

Alternatively, you can invoke delete() on the Zend_Gdata_Gbase_ItemEntry object:

delete($dryRun);
Previous Next
Introduction to Zend Framework
Présentation
Installation
Zend_Acl
Introduction
Affiner les Contrôles d'Accès
Utilisation avancée
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
La théorie du cache
Les frontends Zend_Cache
Les backends Zend_Cache
Zend_Captcha
Introduction
Captcha Operation
Captcha Adapters
Zend_Config
Introduction
Point de vue théorique
Zend_Config_Ini
Zend_Config_Xml
Zend_Console_Getopt
Introduction à Getopt
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 : Zend_Controller_Router_Rewrite
Le dispatcheur
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
Point de vue 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
Validators for Zend_File_Transfer
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 Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction à Gdata
Authentification par procédé AuthSub
Authentification avec ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Utiliser l'API YouTube
Utilisation des albums Web Picasa
Attraper les exceptions Gdata
Zend_Http
Zend_Http_Client - 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
Objets 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
Chargeur de Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported Languages for Locales
Supported Regions for Locales
Zend_Log
Présentation
Rédacteurs (Writers)
Formateurs (mise en forme)
Filtres
Zend_Mail
Introduction
Envoyer des emails en utilisant SMTP
Envoyer plusieurs emails par connexion SMTP
Utiliser différents transports
Email HTML
Fichiers joints
Ajouter des destinataires
Contrôler les limites MIME
Entêtes additionnelles
Jeux de caractères
Encodage
Authentification SMTP
Sécuriser les transports SMTP
Lire des emails
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_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
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_Registry
Utiliser le registre
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
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_Yahoo
Zend_Session
Introduction
Usage basique
Utilisation avancée
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery. Introduction
Class autodiscovering.
Functions autodiscovering.
Autodiscovering. Datatypes.
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_TimeSync
Introduction
Utiliser Zend_TimeSync
Zend_Translate
Introduction
Adaptateurs pour Zend_Translate
Utiliser les adaptateurs de traduction
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Classes de validation standard
Chaînes de validation
Ecrire des validateurs
Zend_Version
Lire la version du Zend Framework
Zend_View
Introduction
Scripts de contrôleur
Scripts de vue
Aides de vue
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Configuration système requise par le Zend Framework
Version de PHP requise
Extensions PHP
Les composants du Zend Framework
Dépendances internes du Zend Framework
Convention de codage PHP du Zend Framework
Vue d'ensemble
Formatage des fichiers PHP
Conventions de nommage
Style de codage
Informations de copyright