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:

// Parameters for ClientAuth authentication
$service = Zend_Gdata_Gbase::AUTH_SERVICE_NAME;
$user = "sample.user@gmail.com";
$pass = "pa$$w0rd";

// Create an authenticated HTTP client
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);

// Create an instance of the Base service
$service = new Zend_Gdata_Gbase($client);

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

/*
 * Retrieve the current URL so that the AuthSub server knows where to
 * redirect the user after authentication is complete.
 */
function getCurrentUrl()
{
    global $_SERVER;

    // Filter php_self to avoid a security vulnerability.
    $php_request_uri =
        htmlentities(substr($_SERVER['REQUEST_URI'],
                            0,
                            strcspn($_SERVER['REQUEST_URI'], "\n\r")),
                     ENT_QUOTES);

    if (isset($_SERVER['HTTPS']) &&
        strtolower($_SERVER['HTTPS']) == 'on') {
        $protocol = 'https://';
    } else {
        $protocol = 'http://';
    }
    $host = $_SERVER['HTTP_HOST'];
    if ($_SERVER['HTTP_PORT'] != '' &&
        (($protocol == 'http://' && $_SERVER['HTTP_PORT'] != '80') ||
        ($protocol == 'https://' && $_SERVER['HTTP_PORT'] != '443'))) {
        $port = ':' . $_SERVER['HTTP_PORT'];
    } else {
        $port = '';
    }
    return $protocol . $host . $port . $php_request_uri;
}

/**
 * Obtain an AuthSub authenticated HTTP client, redirecting the user
 * to the AuthSub server to login if necessary.
 */
function getAuthSubHttpClient()
{
    global $_SESSION, $_GET;

    // If there is no AuthSub session or one-time token waiting for us,
    // redirect the user to the AuthSub server to get one.
    if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
        // Parameters to give to AuthSub server
        $next = getCurrentUrl();
        $scope = "http://www.google.com/base/feeds/items/";
        $secure = false;
        $session = true;

        // Redirect the user to the AuthSub server to sign in

        $authSubUrl = Zend_Gdata_AuthSub::getAuthSubTokenUri($next,
                                                             $scope,
                                                             $secure,
                                                             $session);
         header("HTTP/1.0 307 Temporary redirect");

         header("Location: " . $authSubUrl);

         exit();
    }

    // Convert an AuthSub one-time token into a session token if needed
    if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
        $_SESSION['sessionToken'] =
            Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
    }

    // At this point we are authenticated via AuthSub and can obtain an
    // authenticated HTTP client instance

    // Create an authenticated HTTP client
    $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
    return $client;
}

// -> 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:

// Create an instance of the Base service using an unauthenticated HTTP client
$service = new Zend_Gdata_Gbase();

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 retrieving 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:

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

A full list of these parameters 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:

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

A full list of these parameters 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:

foreach ($feed->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:

foreach ($feed->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:

$service = new Zend_Gdata_Gbase($client);
$newEntry = $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:

// Update the title
$newTitle = "PHP Developer Handbook Second Edition";
$entry->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:

$dryRun = false;
$service->deleteGbaseItem($entry, $dryRun);

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

$dryRun = false;
$entry->delete($dryRun);
Previous Next
Introducción a Zend Framework
Descripción general
Instalación
Aprendiendo Zend Framework
Inicio Rápido con Zend Framework
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Autocarga o Carga automática en Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins en Zend Framework
Introduction
Using Plugins
Conclusion
Primeros pasos con Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Introducción a Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Comprensión y uso de Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Primeros pasos con Zend_Session, Zend_Auth, and Zend_Acl
Building Multi-User Applications With Zend Framework
Managing User Sessions In ZF
Authenticating Users in Zend Framework
Building an Authorization System in Zend Framework
Primeros pasos con Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Primeros pasos con Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Referencia de Zend Framework
Zend_Acl
Introducción
Perfeccionamiento de los controles de acceso
Uso Avanzado
Zend_Amf
Introducción
Zend_Amf_Server
Zend_Application
Introducción
Inicio rápido con Zend_Application
Teoría de Operación
Ejemplos
Funcionalidad Básica
Plugins de Recursos Disponibles
Zend_Auth
Introducción
Tabla de base de datos de autenticación
Autenticación "Digest"
Adaptador de Autenticación HTTP
LDAP Authentication
Autenticación con Open ID
Zend_Barcode
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introducción
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introducción
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introducción
Ejemplos de Zend_CodeGenerator
Referencias de Zend_CodeGenerator
Zend_Config
Introducción
Aspectos Teóricos
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Inicio rápido a Zend_Controller
Conceptos Básicos de Zend_Controller
El Front Controller
La solicitud del Objeto
El Router Standard
El Despachador
Controladores de Acción
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
Excepciones MVC
Zend_Currency
Introduction to Zend_Currency
Using Zend_Currency
Options for currencies
What makes a currency?
Where is the currency?
How does the currency look like?
How much is my currency?
Calculating with currencies
Exchanging currencies
Additional informations on Zend_Currency
Zend_Date
Introducción
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
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
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Mostrar información de variables(Dumping Variables)
Zend_Dojo
Introducción
Zend_Dojo_Data: Envolturas de dojo.data
Ayudantes de Dojo View
Elementos y Decoradores de Dojo Form
Zend_Dojo build layer support
Zend_Dom
Introducción
Zend_Dom_Query
Zend_Exception
Uso de Excepciones
Basic usage
Previous Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_Feed_Writer
Zend_Feed_Pubsubhubbub
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Zend_Filter
Introducción
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Inicio rápido a Zend_Form
Creando elementos de formulario usando Zend_Form_Element
Creando formularios usando Zend_Form
Creando un personalizado marcado de formulario usando Zend_Form_Decorator
Elementos Enviados en el Formulario Estandard de Zend Framework
Decoradores de Formulario (Form Decorartors) estándar contenidos en Zend Framework
Internacionalización de Zend_Form
Uso avanzado de Zend_Form
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introducción
Uso Básico
Uso Avanzado de Zend_Json
Conversión de XML a JSON
Zend_Json_Server - servidor JSON-RPC
Zend_Layout
Introducción
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Cargando archivos y clases dinámicamente
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Zend_Log
Overview
Writers
Formatters
Filters
Using the Factory to Create a Log
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Markup
Introduction
Getting Started With Zend_Markup
Zend_Markup Parsers
Zend_Markup Renderers
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_Oauth
Introduction to OAuth
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introducción
Creando y Cargando Documentos PDF
Guardar Cambios a Documentos PDF
Trabajando con Páginas
Dibujo
Interactive Features
Información del Documento y Metadatos
Ejemplo de Uso del módulo Zend_Pdf
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
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_Serializer
Introduction
Zend_Serializer_Adapter
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 Storage (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_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_DeveloperGarden
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Zend_Service_SlideShare
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_WindowsAzure
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introducción
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool
Using Zend_Tool On The Command Line
Extending Zend_Tool
Zend_Tool_Framework
Introduction
Usando la herramienta CLI
Architecture
Creando Proveedores para usar con Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend_Tool Project Providers
Zend_Tool_Project Internos
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Zend_Uri
Zend_Uri
Zend_Validate
Introducción
Clases de Validación Estándar
Cadenas de Validadores
Escribiendo Validadores
Validation Messages
Zend_Version
Obteniendo la versión de Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introducción
Zend_XmlRpc_Client
Zend_XmlRpc_Server
ZendX_Console_Process_Unix
ZendX_Console_Process_Unix
ZendX_JQuery
Introduction
ZendX_JQuery View Helpers
ZendX_JQuery Form Elements and Decorators
Requisitos de Zend Framework
Versión de PHP
Extensiones de PHP
Componentes de Zend Framework
Dependencias de Zend Framework
Notas de Migración de Zend Framework
Zend Framework 1.10
Zend Framework 1.9
Zend Framework 1.8
Zend Framework 1.7
Zend Framework 1.6
Zend Framework 1.5
Zend Framework 1.0
Zend Framework 0.9
Zend Framework 0.8
Zend Framework 0.6
Estándares de codificación de Zend Framework para PHP
Introducción
Formato de archivos PHP
Convenciones de Nombres
Estilo de código
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Guía de Rendimiento de Zend Framework
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information