Previous Next

The Autoloader

Zend_Loader_Autoloader introduces a comprehensive autoloading solution for Zend Framework. It has been designed with several goals in mind:

  • Provide a true namespace autoloader. (Previous incarnations intercepted all userland namespaces.)

  • Allow registering arbitrary callbacks as autoloaders, and manage them as a stack. (At the time of this writing, this overcomes some issues with spl_autoload, which does not allow re-registering a callback that utilizes an instance method.)

  • Allow optimistic matching of namespaces to provide faster class resolution.

Zend_Loader_Autoloader implements a singleton, making it unversally accessible. This provides the ability to register additional autoloaders from anywhere in your code as necessary.

Using the Autoloader

The first time an instance of the autoloader is retrieved, it registers itself with spl_autoload. You retrieve an instance using the getInstance() method:

$autoloader = Zend_Loader_Autoloader::getInstance();

By default, the autoloader is configured to match the "Zend_" and "ZendX_" namespaces. If you have your own library code that uses your own namespace, you may register it with the autoloader using the registerNamespace() method. For instance, if your library code is prefixed with "My_", you could do so as follows:

$autoloader->registerNamespace('My_');

Nota: Namespace Prefixes

You'll note that the previous example uses "My_" and not "My". This is because Zend_Loader_Autoloader is intended as a general purpose autoloader, and does not make the assumption that a given class prefix namespace includes an underscore. If your class namespace does include one, you should include it when registering your namespace.

You can also register arbitrary autoloader callbacks, optionally with a specific namespace (or group of namespaces). Zend_Loader_Autoloader will attempt to match these first before using its internal autoloading mechanism.

As an example, you may want to utilize one or more eZcomponents components with your Zend Framework application. To use its autoloading capabilities, push it onto the autoloader stack using pushAutoloader():

$autoloader->pushAutoloader(array('ezcBase', 'autoload'), 'ezc');

This tells the autoloader to use the eZcomponents autoloader for classes beginning with "ezc".

You can use the unshiftAutoloader() method to add the autoloader to the beginning of the autoloader chain.

By default, Zend_Loader_Autoloader does no error suppression when using its internal autoloader, which utilizes Zend_Loader::loadClass(). Most of the time, this is exactly what you want. However, there may be cases where you want to suppress them. You can do this using suppressNotFoundWarnings():

$autoloader->suppressNotFoundWarnings(true);

Finally, there may be times when you want the autoloader to load any namespace. For instance, PEAR libraries do not share a common namespace, making specifying individual namespaces difficult when many PEAR components are in use. You can use the setFallbackAutoloader() method to have the autoloader act as a catch-all:

$autoloader->setFallbackAutoloader(true);

Nota: Loading Classes from PHP Namespaces

Starting in version 1.10.0, Zend Framework now allows loading classes from PHP namespaces. This support follows the same guidelines and implementation as that found in the » PHP Framework Interop Group PSR-0 reference implementation.

Under this guideline, the following rules apply:

  • Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.

  • Each "_" character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The "_" character has no special meaning in the namespace.

  • The fully-qualified namespace and class is suffixed with ".php" when loading from the file system.

As examples:

  • \Doctrine\Common\IsolatedClassLoader => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php

  • \namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php

  • \namespace\package_name\Class_Name => /path/to/project/lib/vendor/namespace/package_name/Class/Name.php

Selecting a Zend Framework version

Typically, you will use the version of Zend Framework that the autoloader you instantiate came with. However, when developing a project, it's often useful to track specific versions, major or minor branches, or just the latest version. Zend_Loader_Autoloader, as of version 1.10, offers some features to help manage this task.

Imagine the following scenario:

  • During development, you want to track the latest version of Zend Framework you have installed, so that you can ensure the application works when you upgrade between versions.

    When pushing to Quality Assurance, however, you need to have slightly more stability, so you want to use the latest installed revision of a specific minor version.

    Finally, when you push to production, you want to pin to a specific installed version, to ensure no breakage occurs if or when you add new versions of Zend Framework to you server.

The autoloader allows you to do this with the method setZfPath(). This method takes two arguments, a path to a set of Zend Framework installations, and a version to use. Once invoked, it prepends a path to the include_path pointing to the appropriate Zend Framework installation library.

The directory you specify as your path should have a tree such as the following:

ZendFramework/
|-- 1.9.2/
|   |-- library/
|-- ZendFramework-1.9.1-minimal/
|   |-- library/
|-- 1.8.4PL1/
|   |-- library/
|-- 1.8.4/
|   |-- library/
|-- ZendFramework-1.8.3/
|   |-- library/
|-- 1.7.8/
|   |-- library/
|-- 1.7.7/
|   |-- library/
|-- 1.7.6/
|   |-- library/

(where path points to the directory "ZendFramework" in the above example)

Note that each subdirectory should contain the directory library, which contains the actual Zend Framework library code. The individual subdirectory names may be version numbers, or simply be the untarred contents of a standard Zend Framework distribution tarball/zipfile.

Now, let's address the use cases. In the first use case, in development, we want to track the latest source install. We can do that by passing "latest" as the version:

$autoloader->setZfPath($path, 'latest');

In the example from above, this will map to the directory ZendFramework/1.9.2/library/; you can verify this by checking the return value of getZfPath().

In the second situation, for quality assurance, let's say we want to pin to the 1.8 minor release, using the latest install you have for that release. You can do so as follows:

$autoloader->setZfPath($path, '1.8');

In this case, it will find the directory ZendFramework/1.8.4PL1/library/.

In the final case, for production, we'll pin to a specific version -- 1.7.7, since that was what was available when Quality Assurance tested prior to our release.

$autoloader->setZfPath($path, '1.7.7');

Predictably, it finds the directory ZendFramework/1.7.7/library/.

You can also specify these values in the configuration file you use with Zend_Application. To do so, you'd specify the following information:

[production]
autoloaderZfPath = "path/to/ZendFramework"
autoloaderZfVersion = "1.7.7"

[qa]
autoloaderZfVersion = "1.8"

[development]
autoloaderZfVersion = "latest"

Note the different environment sections, and the different version specified in each environment; these factors will allow Zend_Application to configure the autoloader appropriately.

Advertencia

Performance implications

For best performance, either do not use this feature, or specify a specific Zend Framework version (i.e., not "latest", a major revision such as "1", or a minor revision such as "1.8"). Otherwise, the autoloader will need to scan the provided path for directories matching the criteria -- a somewhat expensive operation to perform on each request.

The Autoloader Interface

Besides being able to specify arbitrary callbacks as autoloaders, Zend Framework also defines an interface autoloading classes may imlement, Zend_Loader_Autoloader_Interface:

interface Zend_Loader_Autoloader_Interface
{
    public function autoload($class);
}

When using this interface, you can simply pass a class instance to Zend_Loader_Autoloader's pushAutoloader() and unshiftAutoloader() methods:

// Assume Foo_Autoloader implements Zend_Loader_Autoloader_Interface:
$foo = new Foo_Autoloader();

$autoloader->pushAutoloader($foo, 'Foo_');

Autoloader Reference

Below, please find a guide to the methods available in Zend_Loader_Autoloader.

Zend_Loader_Autoloader Methods
Method Return Value Parameters Description
getInstance() Zend_Loader_Autoloader N/A

Retrieve the Zend_Loader_Autoloader singleton instance. On first retrieval, it registers itself with spl_autoload. This method is static.

resetInstance() void N/A

Resets the state of the Zend_Loader_Autoloader singleton instance to it's original state, unregistering all autoloader callbacks and all registered namespaces.

autoload($class) string|FALSE
  • $class, required. A string class name to load.

Attempt to resolve a class name to a file and load it.

setDefaultAutoloader($callback) Zend_Loader_Autoloader
  • $callback, required.

Specify an alternate PHP callback to use for the default autoloader implementation.

getDefaultAutoloader() callback N/A

Retrieve the default autoloader implementation; by default, this is Zend_Loader::loadClass().

setAutoloaders(array $autoloaders) Zend_Loader_Autoloader
  • $autoloaders, required.

Set a list of concrete autoloaders to use in the autoloader stack. Each item in the autoloaders array must be a PHP callback.

getAutoloaders() Array N/A

Retrieve the internal autoloader stack.

getNamespaceAutoloaders($namespace) Array
  • $namespace, required

Fetch all autoloaders that have registered to load a specific namespace.

registerNamespace($namespace) Zend_Loader_Autoloader
  • $namespace, required.

Register one or more namespaces with the default autoloader. If $namespace is a string, it registers that namespace; if it's an array of strings, registers each as a namespace.

unregisterNamespace($namespace) Zend_Loader_Autoloader
  • $namespace, required.

Unregister one or more namespaces from the default autoloader. If $namespace is a string, it unregisters that namespace; if it's an array of strings, unregisters each as a namespace.

getRegisteredNamespaces() Array N/A

Returns an array of all namespaces registered with the default autoloader.

suppressNotFoundWarnings($flag = null) boolean|Zend_Loader_Autoloader
  • $flag, optional.

Set or retrieve the value of the flag used to indicate whether the default autoloader implementation should suppress "file not found" warnings. If no arguments or a NULL value is passed, returns a boolean indicating the status of the flag; if a boolean is passed, the flag is set to that value and the autoloader instance is returned (to allow method chaining).

setFallbackAutoloader($flag) Zend_Loader_Autoloader
  • $flag, required.

Set the value of the flag used to indicate whether or not the default autoloader should be used as a fallback or catch-all autoloader for all namespaces.

isFallbackAutoloader() Boolean N/A

Retrieve the value of the flag used to indicate whether or not the default autoloader should be used as a fallback or catch-all autoloader for all namespaces. By default, this is FALSE.

getClassAutoloaders($class) Array
  • $class, required.

Get the list of namespaced autoloaders that could potentially match the provided class. If none match, all global (non-namespaced) autoloaders are returned.

unshiftAutoloader($callback, $namespace = '') Zend_Loader_Autoloader
  • $callback, required. A valid PHP callback

  • $namespace, optional. A string representing a class prefix namespace.

Add a concrete autoloader implementation to the beginning of the internal autoloader stack. If a namespace is provided, that namespace will be used to match optimistically; otherwise, the autoloader will be considered a global autoloader.

pushAutoloader($callback, $namespace = '') Zend_Loader_Autoloader
  • $callback, required. A valid PHP callback

  • $namespace, optional. A string representing a class prefix namespace.

Add a concrete autoloader implementation to the end of the internal autoloader stack. If a namespace is provided, that namespace will be used to match optimistically; otherwise, the autoloader will be considered a global autoloader.

removeAutoloader($callback, $namespace = '') Zend_Loader_Autoloader
  • $callback, required. A valid PHP callback

  • $namespace, optional. A string representing a class prefix namespace, or an array of namespace strings.

Remove a concrete autoloader implementation from the internal autoloader stack. If a namespace or namespaces are provided, the callback will be removed from that namespace or namespaces only.

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