Previous Next

Zend_Http_UserAgent

Overview

With the plethora of mobile devices available on the market, it's increasingly important to be able to identify the capabilities of those devices in order to present content in a an appropriate way. For instance, if the device is not capable of displaying images, you might want to omit them from the markup; alternately, if a device is capable of Flash, you may want to provide a Flash-based user interface.

The process of identifying a device's capabilities typically first requires knowing the HTTP User Agent, and then comparing that user agent against a database of user agent capabilities. Zend_Http_UserAgent was created to provide these capabilities for your applications. It consists of several major features:

  • The primary Zend_Http_UserAgent class, which detects the User Agent, and gives you a device object, as well as persists the device object for later retrieval.

  • A Zend_Http_UserAgent_Device interface, and a number of implementations that implement it. These objects utilize a features adatper to discover device capabilities, and then allow you to introspect those capabilities.

  • A Zend_Http_UserAgent_Features_Adapter interface; concrete implementations provide the ability to discover device capabilities, or features.

  • A Zend_Http_UserAgent_Storage interface, which is used to persist discovered devices for given users, allowing for faster device capability discovery on subsequent page visits.

  • A view helper that can be used within your view scripts and layouts to branch display logic based on device capabilities.

  • A Zend_Application resource for configuring and instantiating the user agent object, as well as seeding the view helper with the user agent object instance.

At the time of this writing, The UserAgent component provides three adapters:

Quick Start

First, you will need to download the following:

  • The WURFL » PHP API. This archive contains the most recent wurfl-latest.xml file and patches which constitute the actual WURFL database.

We suggest that you inflate this archive in your "library" directory. Inflating the archive will create a wurfl-php-1.1 directory.

library
|-- wurfl-php-1.1
|   |-- COPYING
|   |-- docs
|   |-- examples
|   |-- README
|   |-- tests
|   `-- WURFL

Next, create a data and cache directory for the WURFL database and related cache files; this should be done from your project root (the directory containing the application and library directories). When you do so, make sure the directory is at least writable by the web server user; the following makes it writable for all users.

mkdir -p data/wurfl/cache
chmod -R o+rwX data/wurfl/cache

Now, copy the WURFL data from the inflated archive into your data directory.

cp library/wurfl-php-1.1/tests/resources/wurfl-latest.zip data/wurfl/
cp library/wurfl-php-1.1/tests/resources/web_browsers_patch.xml data/wurfl/

Create a WURFL configuration file named application/configs/wurfl-config.php, with the following contents:




        

Finally, edit your application.ini to add the following lines to your [production] section:

resources.useragent.wurflapi.wurfl_api_version = "1.1"
resources.useragent.wurflapi.wurfl_lib_dir = APPLICATION_PATH "/../library/wurfl-php-1.1/WURFL/"
resources.useragent.wurflapi.wurfl_config_file = APPLICATION_PATH "/configs/wurfl-config.php"

Note:

The trailing directory separator on the wurfl_lib_dir setting is important. The WURFL API does no normalization, and expects it to be there.

At this point, everything is setup. The first request (from a mobile device) will populate the WURFL cache by parsing the resources/wurfl.xml file, and as such may take up to a minute. After that, lookups will be quite fast, and each request will contain detailed information on the user agent.

You can access this information in a variety of ways. From within the MVC portion of your application, you can access it via the bootstrap. Within plugins, this is done by grabbing the bootstrap from the front controller.

$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$userAgent = $bootstrap->getResource('useragent');

From your action controller, use getInvokeArg() to grab the bootstrap, and from there, the user agent object.

$bootstrap = $this->getInvokeArg('bootstrap');
$userAgent = $bootstrap->getResource('useragent');

Within your view, you can grab it using the UserAgent view helper.

$userAgent = $this->userAgent();

Once you have the user agent object, you can query it for different capabilities. As one example, you may want to use an alternate layout script based on the user agent capabilities.

$width = $userAgent->getDevice()->getPhysicalScreenWidth();
switch (true) {
    case ($width <= 128):
        $layout->setLayout('layout-poor');
        break;
    case ($width <= 176):
        $layout->setLayout('layout-medium');
        break;
    case ($width <= 240):
        $layout->setLayout('layout-high');
        break;
    case ($width <= 320):
        $layout->setLayout('layout-ultra');
        break;
    default:
        // use default
        break;
}

Finally, each device will often have a large number of capabilities not immediately represented in the device interface. You can query these using the hasFeature() and getFeature() methods.

if ($userAgent->hasFeature('mp3') && $userAgent->getFeature('mp3')) {
    // embed HTML5 audio tag...
}

Configuration Options

UserAgent Options

The following options may be passed to the constructor or within your application configuration. A "." indicates another layer of depth in the configuration array; as an example, assigning "wurflapi.wurfl_config_array.wurfl.main-file" as part of a PHP configuration would require the following definition:

$config = array(
    'wurflapi' => array(
        'wurfl_config_array' => array(
            'wurfl' => array(
                'main-file' => 'path/to/some/file',
            ),
        ),
    ),
);

Each features adapter has its own options available as well, which may be mixed in with the general UserAgent options.

browser_type

Used to seed the list of devices the component will search. See also identification_sequence; this value will be prepended to that list during user agent device discovery.

http_accept

The value of the Accept HTTP header; used by some user agents to determine capabilities. Set this to seed the value explicitly.

identification_sequence

A comma-separated list of device types to scan for matches; defaults to "mobile,desktop".

storage.adapter

The name of a storage adapter used to persist the device capabilities, typically within a given user session. The value may either be a fully qualified class name, or a short name to resolve by the plugin loader for storage classes. By default, uses "Session" as the value, resolving to Zend_Http_UserAgent_Storage_Session.

storage.options[]

An array of options to pass to the constructor of a storage adapter. By default, the option browser_type will be present.

plugin_loader.[type] = [class]

Plugin loader configuration; allows you to specify a pre-configured Zend_Loader_PluginLoader extension class to use for one of the plugin loader types managed by UserAgent (currently "storage" and "device".

server[]

Typically, you will not set this; this simply allows injection of the $_SERVER superglobal (or a filtered version of it). The value should be an associative array.

user_agent

The actual HTTP User-Agent string you wish to try and match. Typically, this will be auto-discovered from the server array.

[browser_type].device.classname

The device class to use for a given browser type; typically, browser_type will be one of the supported browser devices, including:

  • Bot

  • Checker

  • Console

  • Desktop

  • Email

  • Feed

  • Mobile

  • Offline

  • Probe

  • Spam

  • Text

  • Validator

The browser_type should be normalized to lowercase for configuration purposes.

[browser_type].device.path and [browser_type].device.prefix

An alternate way to specify the device class for a given browser type is to assume it is named after the device, and that all device classes are in the same path sharing the same prefix. Configure the prefix and path using these keys.

As an example, the following would look for a class named "Mobile_Device_Bot" on the path "Mobile/Device/" under the application library.

resources.useragent.bot.device.path = APPLICATION_PATH '/../library/Mobile/Device"
resources.useragent.bot.device.prefix = "Mobile_Device"
[browser_type].features.path and [browser_type].features.classname

These settings are used to load the features capabilities detection class for a given browser type. The class will be named using the classname key, and is expected to exist in the file denoted by the path key. The class should implement Zend_Http_UserAgent_Features_Adapter.

wurflapi.wurfl_api_version

If using the WURFL API, use this key to specify which version you are using; typically, this will be either "1.0" or "1.1".

wurflapi.wurfl_lib_dir

If using the WURFL API, use this key to specify in which directory the library exists.

wurflapi.wurfl_config_file

If using the WURFL API, use this key to specify the location of the configuration file you will use; typically, this will be resources/wurfl-config.php within the wurfl_lib_dir.

wurflapi.wurfl_config_array.wurfl.main-file

If using version 1.1 of the WURFL API, you can omit using a wurfl_config_file, and instead provide an associative array of configuration values. This particular value indicates the location of the wurfl.xml file containing the actual WURFL database.

wurflapi.wurfl_config_array.wurfl.patches[]

If using version 1.1 of the WURFL API, you can omit using a wurfl_config_file, and instead provide an associative array of configuration values. This particular value is an array of file locations containing patchfiles for the wurfl.main-file (which are used to ammend and extend the primary database file).

wurflapi.wurfl_config_array.persistence.provider

If using version 1.1 of the WURFL API, you can omit using a wurfl_config_file, and instead provide an associative array of configuration values. This particular value indicates the type of persistence provider used when caching discovered capabilities. See the WURFL documentation for potential values; "file" is a known good value.

wurflapi.wurfl_config_array.persistence.dir

If using version 1.1 of the WURFL API, you can omit using a wurfl_config_file, and instead provide an associative array of configuration values. This particular value indicates the location where the persistence provider will cache discovered capabilities.

Available Methods

__construct ( $options = null )

The constructor attempts to determine the current User-Agent based on the options provided, the current request information, and/or previously discovered information persisted in storage. Once instantiated, the detected device is immediately available.

Please see configuration options section for details on the $options array.

serialize ( )

Defined by the Serializable interface, this method performs logic necessary to determine what within the object should be serialized when the object is serialized by a storage adapter.

unserialize ( $serialized )

Defined by the Serializable interface, this method performs logic necessary to determine how to unserialize a previously serialized instance.

setOptions ( $options )

Initializes object state. Please see the configuration options section for information on the $options array.

getUserAgent ( )

Retrieve the discovered User-Agent string. Unless set explicitly, this will be autodiscovered from the server array.

setUserAgent ( $userAgent )

Set the User-Agent string explicitly. Once getDevice() has been called, this property is marked immutable, and calling this method will raise an exception.

getHttpAccept ( $httpAccept = null )

Retrieve the HTTP Accept header value.

setHttpAccept ( $httpAccept )

Explicitly set the HTTP Accept header value. Once getDevice() has been called, this property is marked immutable, and calling this method will raise an exception.

getStorage ( $browser = null )

Retrieves a persistent storage object for a given browser type.

setStorage ( Zend_Http_UserAgent_Storage $storage )

Use this to explicitly set the peristent storage object. Once getDevice() has been called, the storage is marked immutable (as in: you may not inject a new storage object), and calling this method will raise an exception.

clearStorage ( $browser = null )

Clears any information in the persistent storage object.

getConfig ( )

Retrieve configuration parameters.

getDevice ( )

Use this method to get the User-Agent Device object; this is the object that will contain the various discovered device capabilities.

Discovery of the User-Agent device occurs in this method. Once the device has been retrieved, the server array, browser type, user agent, http accept, and storage properties are marked as immutable.

getBrowserType ( )

Retrieve the discovered browser type; usually one of:

  • Bot

  • Checker

  • Console

  • Desktop

  • Email

  • Feed

  • Mobile

  • Offline

  • Probe

  • Spam

  • Text

  • Validator

Unless explicitly set, the browser type is unknown until getDevice() has been called.

setBrowserType ( $browserType )

Explicitly set the browser type to prepend to the identification sequence. Once getDevice() has been called, the browser type is marked immutable, and calling this method will raise an exception.

getServer ( )

Retrieve the array of HTTP headers and environment variables used to perform device discovery. If the array has not yet been set, it is seeded with the $_SERVER superglobal.

setServer ( $server )

Explicitly set the "server" array of HTTP headers and environment variables to use during device discovery. Once getDevice() has been called, the server array is marked immutable, and calling this method will raise an exception.

getServerValue ( $key )

Retrieve a single value from the server array by key.

setServerValue ( $key, $value )

Overwrite or define a value in the internal server array. Once getDevice() has been called, the server array is marked immutable, and calling this method will raise an exception.

setPluginLoader ( $type, $loader )

$type may be one of "device" or "storage; the former is used when attempting to find device classes, the latter for finding storage classes. $loader may be a Zend_Loader_PluginLoader instance, or a string name containing the classname of a Zend_Loader_PluginLoader extension class.

getPluginLoader ( $type )

Retrieves either the "device" or "storage" plugin loader instance.

Examples

Please see the quick start for examples at this time.

Previous Next
Introduction to Zend Framework
Overview
Installation
Learning Zend Framework
Zend Framework Quick Start
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Autoloading in Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins in Zend Framework
Introduction
Using Plugins
Conclusion
Getting Started with Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Getting Started Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Understanding and Using Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Getting Started with 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
Getting Started with Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Getting Started with Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Zend Framework Reference
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Barcode
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
SimpleCloud API: Zend_Cloud
Document Service Introduction
Queue Service Introduction
StorageService Introduction
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Json
Zend_Config_Xml
Zend_Config_Yaml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
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
Introduction
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
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
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
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
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
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_Http_UserAgent
The UserAgent Device Interface
The UserAgent Features Adapter
The WURFL UserAgent Features Adapter
The DeviceAtlas UserAgent Features Adapter
The TeraWurfl UserAgent Features Adapter
The UserAgent Storage Interface
The Session UserAgent Storage Adapter
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
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
Loading Files and Classes Dynamically
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
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Interactive Features
Document Info and Metadata
Zend_Pdf module usage example
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_Ebay
Zend_Service_Ebay_Finding
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_ShortUrl
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_WindowsAzure_Storage_Blob
Zend_Service_WindowsAzure_Diagnostics_Manager
Zend_Service_WindowsAzure_Storage_Queue
Zend_Service_WindowsAzure_Storage_Table
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
Introduction
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
Using the CLI Tool
Architecture
Creating Providers to use with 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 Internals
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
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
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
Zend Framework Requirements
Introduction
Zend Framework Migration Notes
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
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
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
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information