|
|
Aquí encontrará documentación del tipo API sobre todos los recursos de
plugins disponibles por defecto en Zend_Application.
Zend_Application_Resource_Cachemanager may be
utilised to configure a set of Zend_Cache option
bundles for use when lazy loading caches using
Zend_Cache_Manager
As the Cache Manager is a lazy loading mechanism, the options are translated to option templates used to instantiate a cache object on request.
Ejemplo #1 Sample Cachemanager resource configuration
Below is a sample INI file showing how
Zend_Cache_Manager may be configured. The format
is the Cachemanager resource prefix (resources.cachemanager)
followed be the name to assign to an option cache template or bundle (e.g.
resources.cachemanager.database) and finally followed by a
typical Zend_Cache option.
resources.cachemanager.database.frontend.name = Core resources.cachemanager.database.frontend.customFrontendNaming = false resources.cachemanager.database.frontend.options.lifetime = 7200 resources.cachemanager.database.frontend.options.automatic_serialization = true resources.cachemanager.database.backend.name = File resources.cachemanager.database.backend.customBackendNaming = false resources.cachemanager.database.backend.options.cache_dir = "/path/to/cache" resources.cachemanager.database.frontendBackendAutoload = false
Actually retrieving this cache from the Cache Manager is as simple as
accessing an instance of the Manager (Zend_Cache_Manager)
retrieved from Zend_Application_Resource_Cachemanager and
calling Zend_Cache_Manager::getCache('database'). The example
below is taken from a controller where the bootstrap class can be accessed as
a Front Controller parameter (which is automatically assigned during bootstrapping).
As you can see, the Cache Manager Resource implements a
getCacheManager() method to retrieve the bootstrapped instance
of Zend_Cache_Manager.
$manager = $this->getFrontController()
->getParam('bootstrap')
->getResource('cachemanager')
->getCacheManager();
$dbCache = $manager->getCache('database');
See Zend_Cache::factory() method to get a description of the default values you can assign when configuring a cache via a configuration file such as out example INI file above.
Zend_Application_Resource_Db
inicializará un adaptador
Zend_Db
basado en las opciones que se le pasen. Por defecto,
también establece el adaptador por
defecto para usarlo con
Zend_Db_Table
.
Zend_Db_Table. If you want to use mutliple databases
simultaneously, you can use the Multidb Resource
Plugin.
Se reconocen las siguientes configuraciones claves:
adapter
: tipo de adaptador
Zend_Db
.
params : array asociativo de parámetros de configuración para utilizar al recuperar la instancia del adaptador.
isDefaultTableAdapter : Indica si establecer o no este adaptador como el adaptador de tablas por defecto.
Ejemplo #2 Muestra de la Configuracion de Recursos del Adaptador DB (Base de Datos)
A continuación, un ejemplo de configuración INI que puede ser utilizada para iniciar el recurso DB.
[production] resources.db.adapter = "pdo_mysql" resources.db.params.host = "localhost" resources.db.params.username = "webuser" resources.db.params.password = "XXXXXXX" resources.db.params.dbname = "test" resources.db.isDefaultTableAdapter = true
Nota: Recuperando la Instancia del Adaptador
Si decide no hacer la instanciación del adaptador con este recurso por defecto del adaptador de tabla, ¿cómo puede recuperar la instancia del adaptador?
Como con cualquier recurso de plugin, se puede recuperar el recurso de plugin de DB desde su archivo de arranque:
$resource = $bootstrap->getPluginResource('db');Una vez que tiene el recurso objeto, puede recuperar el adaptador de DB usando el método getDbAdapter() :
$db = $resource->getDbAdapter();
Probablemente el recurso más común que se carga con
Zend_Application
será el recurso Front Controller
, que proporciona la habilidad para configurar
Zend_Controller_Front
. Este recurso ofrece
la posibilidad de establecer parámetros arbitrarios del Front
Controller,
especificar plugins para inicializar, y mucho más.
Una vez inicializado, el recurso asigna la propiedad del
$frontController
del bootstrap a la instancia
Zend_Controller_Front
.
Las claves de configuración disponibles incluyen las siguientes, sin importar si son mayúsculas ó minúsculas:
controllerDirectory :: ya sea un valor de string especificando un único directorio controlador, o un array de pares de directorio módulo/controlador.
moduleControllerDirectoryName : un valor de string indicando el subdirectorio bajo el cual un módulo contiene controladores.
moduleDirectory : directorio bajo el cual pueden encontrarse los módulos.
defaultControllerName : Nombre base del controlador por defecto (normalmente, "índex").
defaultAction : nombre base de la acción por defecto (normalmente, "índex").
defaultModule : nombre base del módulo por defecto (normalmente, "default").
baseUrl : base explícita a la URL de la aplicación (normalmente auto-detect).
plugins : array con los nombres de los plugins de las clases de los Front Controllers. El recurso instanciará a cada clase (sin argumentos al constructor) y luego registra la instancia con el Front Controller.
params : array de pares clave/valor para registrarse con el front controller.
Si se ingresa una clave no reconocida, ésta será registrada como un parámetro de Front Controller pasándolo a setParam() .
Ejemplo #3 Ejemplo Front Controller resource configuration
A continuación, INI es un snippet para mostrar cómo configurar el recurso Front Controller.
[production] resources.frontController.controllerDirectory = APPLICATION_PATH . "/controllers" resources.frontController.moduleControllerDirectoryName = "actions" resources.frontController.moduleController = APPLICATION_PATH . "/modules" resources.frontController.defaultControllerName = "site" resources.frontController.defaultAction = "home" resources.frontController.defaultModule = "static" resources.frontController.baseUrl = "/subdir" resources.frontController.plugins.foo = "My_Plugin_Foo" resources.frontController.plugins.bar = "My_Plugin_Bar" resources.frontController.env = APPLICATION_ENV
Ejemplo #4 Recuperar el Front Controller de su arranque (bootstrap)
Una vez que el recurso de su Front Controller ha sido inicializado, se puede recuperar la instancia de Front Controller a través de la propiedad $frontController de su bootstrap.
$bootstrap->bootstrap('frontController');
$front = $bootstrap->frontController;
Zend_Application_Resource_Layout can be used to
configure Zend_Layout. Configuration options are
per the Zend_Layout
options.
Ejemplo #5 Sample Layout configuration
Below is a sample INI snippet showing how to configure the layout resource.
resources.layout.layout = "NameOfDefaultLayout" resources.layout.layoutPath = "/path/to/layouts"
Zend_Application_Resource_Locale can be used to
set an application-wide locale which is then used in all classes and components
which work with localization or internationalization.
There are basically three usecases for the Locale Resource Plugin. Each of them should be used depending on the applications need.
Without specifying any options for
Zend_Application_Resource_Locale,
Zend_Locale will detect the locale, which your application will
use, automatically.
This detection works because your client sends the wished language within his
HTTP request. Normally the clients browser sends the languages he
wants to see, and Zend_Locale uses this information for
detection.
But there are 2 problems with this approach:
The browser could be setup to send no language
The user could have manually set a locale which does not exist
In both cases Zend_Locale will fallback to other mechanism to
detect the locale:
When a locale has been set which does not exist,
Zend_Locale tries to downgrade this string.
When, for example, en_ZZ is set it will automatically be degraded to en. In this case en will be used as locale for your application.
When the locale could also not be detected by downgrading, the locale of your environment (web server) will be used. Most available environments from Web Hosters use en as locale.
When the systems locale could not be detected Zend_Locale
will use it's default locale, which is set to en per
default.
For more informations about locale detection take a look into this chapter on Zend_Locale's automatic detection.
The above autodetection could lead to problems when the locale could not be detected and
you want to have another default locale than en. To prevent this,
Zend_Application_Resource_Locale allows you to set a own locale
which will be used in the case that the locale could not be detected.
Ejemplo #6 Autodetect locale and setting a fallback
The following snippet shows how to set a own default locale which will be used when the client does not send a locale himself.
; Try to determine automatically first, ; if unsuccessful, use nl_NL as fallback. resources.locale.default = "nl_NL"
Sometimes it is useful to define a single locale which has to be used. This can be done by using the force option.
In this case this single locale will be used and the automatic detection is turned off.
Ejemplo #7 Defining a single locale to use
The following snippet shows how to set a single locale for your entire application.
; No matter what, the nl_NL locale will be used. resources.locale.default = "nl_NL" resources.locale.force = true
Zend_Application_Resource_Log to instantiate a
Zend_Log instance with an arbitrary number of log writers.
Configuration will be passed to the Zend_Log::factory() method,
allowing you to specify combinations of log writers and filters. The log instance may then
be retrieved from the bootstrap later in order to log events.
Ejemplo #8 Sample Log Resource Configuration
Below is a sample INI snippet showing how to configure the log resource.
resources.log.stream.writerName = "Stream" resources.log.stream.writerParams.stream = APPLICATION_PATH "/../data/logs/application.log" resources.log.stream.writerParams.mode = "a" resources.log.stream.filterName = "Priority" resources.log.stream.filterParams.priority = 4
For more information on available options, please review the Zend_Log::factory() documentation.
Zend_Application_Resource_Mail can be used
to instantiate a transport for Zend_Mail or set
the default name and address, as well as the default replyto- name and address.
When instantiating a transport, it's registered automatically to
Zend_Mail. Though, by setting the
transport.register directive to FALSE, this
behaviour does no more occur.
Ejemplo #9 Sample Mail Resource Configuration
Below is a sample INI snippet showing how to configure the mail resource plugin.
resources.mail.transport.type = smtp resources.mail.transport.host = "smtp.example.com" resources.mail.transport.auth = login resources.mail.transport.username = myUsername resources.mail.transport.password = myPassword resources.mail.transport.register = true ; True by default resources.mail.defaultFrom.email = john@example.com resources.mail.defaultFrom.name = "John Doe" resources.mail.defaultReplyTo.email = Jane@example.com resources.mail.defaultReplyTo.name = "Jane Doe"
Zend_Application_Resource_Modules se utiliza para
inicializar sus módulos de aplicación. Si su módulo tiene un archivo
Bootstrap.php en su raíz, y contiene una clase
llamada Module_Bootstrap (donde "Module" es el
nombre del módulo), entonces usará esa clase para arrancar el módulo.
Por defecto, se creará una instancia de
Zend_Application_Module_Autoloader para el
módulo, utilizando el nombre del módulo y del directorio para
inicializarlo.
Ya que los módulos no reciben ningún parámetro por defecto, para poder activarlos via configuración, será necesario crearlo como un array vacío. Seguiendo el estilo de configuración INI será similar a:
resources.modules[] =
Siguiendo el estilo de configuración XML será similar a:
Utilizando un array PHP estandar, simplemente creelo como un array vacío:
$options = array(
'resources' => array(
'modules' => array(),
),
);
Nota: Dependencia de Recursos del Front Controller
El recurso Modules tiene una dependencia de Front Controller resource . Usted puede, por supuesto, proporcionar su propia sustitución de ese recurso mediante un recurso personalizado de la clase Front Controller o un método inicializador de la clase -- tan largo como se quiera siempre que el plugin del recurso de la clase termine en "Frontcontroller" o el método inicializador se llame "_initFrontController" (case insensible).
Ejemplo #10 Configurando Módulos
Usted puede especificar una configuración específica de un módulo utilizando el nombre del módulo como un prefijo/sub-sección en su archivo de configuración.
Por ejemplo, supongamos que su aplicación tiene un módulo "noticias". Los siguientes son ejemplos de INI y XML que muestran la configuración de recursos en ese módulo.
[production] news.resources.db.adapter = "pdo_mysql" news.resources.db.params.host = "localhost" news.resources.db.params.username = "webuser" news.resources.db.params.password = "XXXXXXX" news.resources.db.params.dbname = "news" news.resources.layout.layout = "news"
pdo_mysql localhost webuser XXXXXXX news true
Ejemplo #11 Recuperando el bootstrap de un módulo específico
En ocasiones, puede que necesite para recuperar el objeto bootstrap de un módulo específico -- tal vez para ejecutar discretos métodos bootstrap ,o a recoger el cargador automático con el fin de configurarlo. Esto puede hacerse utilizando el método getExecutedBootstraps() de los recursos de Módulo.
$resource = $bootstrap->getPluginResource('modules');
$moduleBootstraps = $resource->getExecutedBootstraps();
$newsBootstrap = $moduleBootstraps['news'];
Zend_Application_Resource_Multidb is used to initialize
multiple Database connections. You can use the same options as you can with
the Db Resource Plugin.
However, for specifying a default connection, you can also use the 'default' directive.
Ejemplo #12 Setting up multiple Db Connections
Below is an example INI configuration that can be used to initialize two Db Connections.
[production] resources.multidb.db1.adapter = "pdo_mysql" resources.multidb.db1.host = "localhost" resources.multidb.db1.username = "webuser" resources.multidb.db1.password = "XXXX" resources.multidb.db1.dbname = "db1" resources.multidb.db2.adapter = "pdo_pgsql" resources.multidb.db2.host = "example.com" resources.multidb.db2.username = "dba" resources.multidb.db2.password = "notthatpublic" resources.multidb.db2.dbname = "db2" resources.multidb.db2.default = true
Ejemplo #13 Retrieving a specific database adapter
When using this resource plugin you usually will want to retrieve
a specific database. This can be done by using the resource's
getDb(). The method
getDb() returns an instance of a class that
extends Zend_Db_Adapter_Abstract. If you have not
set a default database, an exception will be thrown when this method
is called without specifying a parameter.
$resource = $bootstrap->getPluginResource('multidb');
$db1 = $resource->getDb('db1');
$db2 = $resource->getDb('db2');
$defaultDb = $resource->getDb();
Ejemplo #14 Retrieving the default database adapter
Additionally, you can retrieve the default database adapter by using the method getDefaultDb(). If you have not set a default adapter, the first configured db adapter will be returned. Unless you specify FALSE as first parameter, then NULL will be returned when no default database adapter was set.
Below is an example that assumes the Multidb resource plugin has been configured with the INI sample above:
$resource = $bootstrap->getPluginResource('multidb');
$db2 = $resource->getDefaultDb();
// Same config, but now without a default db:
$db1 = $resource->getDefaultDb();
$null = $resource->getDefaultDb(false); // null
Zend_Application_Resource_Navigation can be used to configure
a Zend_Navigation instance. Configuration options are per the
Zend_Navigation options.
Once done configuring the navigation instance, it assigns the instance to
Zend_View_Helper_Navigation by default
-- from which you may retrieve it later.
Ejemplo #15 Sample Navigation resource configuration
Below is a sample INI snippet showing how to configure the navigation resource.
resources.navigation.pages.page1.label = "Label of the first page" resources.navigation.pages.page1.route = "Route that belongs to the first page" ; Page 2 is a subpage of page 1 resources.navigation.pages.page1.pages.page2.type = "Zend_Navigation_Page_Uri" resources.navigation.pages.page1.pages.page2.label = "Label of the second page" resources.navigation.pages.page1.pages.page2.uri = "/url/to/page/2"
Zend_Application_Resource_Router can be used to
configure the router as it is registered with the Front Controller.
Configuration options are per the
Zend_Controller_Router_Route options.
Ejemplo #16 Sample Router Resource configuration
Below is a sample INI snippet showing how to configure the router resource.
resources.router.routes.route_id.route = "/login" resources.router.routes.route_id.defaults.module = "user" resources.router.routes.route_id.defaults.controller = "login" resources.router.routes.route_id.defaults.action = "index" ; Optionally you can also set a Chain Name Separator: resources.router.chainNameSeparator = "_"
For more information on the Chain Name Separator, please see its section.
Zend_Application_Resource_Session
le permite
configurar
Zend_Session
y opcionalmente
inicializar una sesión SaveHandler.
Para establecer un manejador de sesiones, simplemente pasar al recurso la clave opcional saveHandler (case insensible). El valor de esta opción puede ser uno de los siguientes:
String
: un string indicando una clase implementando
Zend_Session_SaveHandler_Interface
que
debería ser instanciada.
Array
: un array con las claves "class" y,
opcionalmente, "options", indicando la clase que implementa
Zend_Session_SaveHandler_Interface
que
debería ser instanciada y una variedad de opciones para proporcionar
a su constructor.
Zend_Session_SaveHandler_Interface
: un objeto
implementando esta interfaz.
Pasando cualquier otra opción de claves será pasado a
Zend_Session::setOptions()
para configurar
Zend_Session
.
Ejemplo #17 Configuración de recursos de la Sesión Ejemplo
A continuación el snippet
INI
nos muestra cómo configurar el recurso
para sesiones. Se establecen varias opciones
Zend_Session
, como también configura una
instancia
Zend_Session_SaveHandler_DbTable
.
resources.session.save_path = APPLICATION_PATH "/../data/session" resources.session.use_only_cookies = true resources.session.remember_me_seconds = 864000 resources.session.saveHandler.class = "Zend_Session_SaveHandler_DbTable" resources.session.saveHandler.options.name = "session" resources.session.saveHandler.options.primary.session_id = "session_id" resources.session.saveHandler.options.primary.save_path = "save_path" resources.session.saveHandler.options.primary.name = "name" resources.session.saveHandler.options.primaryAssignment.sessionId = "sessionId" resources.session.saveHandler.options.primaryAssignment.sessionSavePath = "sessionSavePath" resources.session.saveHandler.options.primaryAssignment.sessionName = "sessionName" resources.session.saveHandler.options.modifiedColumn = "modified" resources.session.saveHandler.options.dataColumn = "session_data" resources.session.saveHandler.options.lifetimeColumn = "lifetime"
Nota: Configurando tu primera base de datos!
Si vas a configurar el manejador
Zend_Session_SaveHandler_DbTablepara guardar sesiones , primero deberas configurar tu conexión a la base de datos. Lo puedes hacer mediante Db -- y asegurate de que la llave " resources.db " esta antes que el " resources.session " -- o escribiedo tu propia clase para inicializar la base de datos y establecer los valores predeterminados para el adaptadorZend_Db_Table.
Zend_Application_Resource_View
puede ser
utilizada para configurar una instancia
Zend_View
.
Las opciones de configuración son por
las opciones de
Zend_View
.
Una vez hecha la configuración de la instancia de vista, crea una
instancia de
Zend_Controller_Action_Helper_ViewRenderer
y
registra el ViewRenderer con
Zend_Controller_Action_HelperBroker
-- desde la
cual usted puede recuperarla posteriormente.
Ejemplo #18 Ejemplo de configuración del recurso Vista
A continuación un snippet INI mostrando cómo configurar el recurso vista (view).
resources.view.encoding = "UTF-8" resources.view.basePath = APPLICATION_PATH "/views/scripts"
|
|
Copyright © 2005-2011 Zend Technologies Inc (compiled by mikaelkael with ZFDocumentor - SVN 20189).

