El Front ControllerIntroducciónZend_Controller_Front implementa un Front
Controller pattern usado en aplicaciones Model-View-Controller
(MVC).
Su propósito es inicializar el medio ambiente de la solicitud,
rutear la solicitud entrante, y luego hacer un dispatch de
cualquier de las acciones descubiertas; le agrega las respuestas
y las regresa cuando se completa el proceso.
Zend_Controller_Front también implementa el Singleton
pattern, significando que solo una única instancia de él
puede estar disponible en cualquier momento dado.
Esto le permite actuar también como un registro en el que los demás
objetos puden extraer del proceso dispatch.
Zend_Controller_Front registra un plugin broker consígo
mismo, permitiendo que diversos eventos que dispara sean observados
por plugins. En muchos casos, esto da el desarrollador la
oportunidad de adaptar el proceso de dispatch al sitio sin la
necesidad de ampliar el Front Controller para añadir funcionalidad.
Como mínimo, el front controller necesita una o más paths a
directorios que contengan
action controllers a fin de hacer su trabajo.
Una variedad de métodos también pueden ser invocados para seguir
adaptando el medio ambiente del front controller y ese a sus
helper classes.
Comportamiento por Defecto
Por defecto, el front controller carga el ErrorHandler
plugin, así como al ViewRenderer
action helper plugin. Estos son para simplificar el manejo de
errores y el view renderering en sus controladores, respectivamente.
Para deshabilitar el ErrorHandler, ejecutar lo
siguiente en cualquier momento antes de llamar a
dispatch():
setParam('noErrorHandler', true);
]]>
Para deshabilitar el ViewRenderer, haga lo
siguiente antes de llamar a dispatch():
setParam('noViewRenderer', true);
]]>Métodos Básicos
El front controller tiene varios accessors para establecer su
medio ambiente. Sin embargo, hay tres métodos básicos clave para la
funcionalidad del front controller:
getInstance()getInstance() se utiliza para recuperar una
instancia del front controller. Como el front controller
implementa un patrón Singleton, este también es el único
medio posible para instanciar un objeto front controller.
setControllerDirectory() y addControllerDirectorysetControllerDirectory() se usa para decirle a the dispatcher
dónde buscar para los archivos de clase action controller.
Acepta bien un único path o un array asociativo de pares
módulo/path.
Como algunos ejemplos:
setControllerDirectory('../application/controllers');
// Establecer varios directorios módulos a la vez:
$front->setControllerDirectory(array(
'default' => '../application/controllers',
'blog' => '../modules/blog/controllers',
'news' => '../modules/news/controllers',
));
// Agregar un directorio de módulos 'foo':
$front->addControllerDirectory('../modules/foo/controllers', 'foo');
]]>
Si usa addControllerDirectory() sin un nombre
de módulo, este establecerá el directorio
default para el módulo -- sobreescribiéndolo
si ya existe.
Puede conseguir la configuración actual para el directorio del
controlador utilizando getControllerDirectory();
este devolverá un array de pares módulo/directorio.
addModuleDirectory() y getModuleDirectory()
Uno de los aspectos del front controller es que puede definir una estructura
modular de directorio para crear componentes
standalone; estos son llamados "módulos".
Cada módulo debe estar en su propio directorio y ser un espejo
de la estructura del directorio del módulo por defecto -- es
decir, que debería tener como mínimo un subdirectorio de
"controladores", y típicamente un subdirectorio de "views"
y otros subdirectorios de aplicaciones.
addModuleDirectory() permite pasar el nombre de
un directorio que contiene uno o más directorios de módulos.
A continuación lo analiza y los añade como directorios de
controladores al front controller.
Después, si quiere determinar el path a un determinado módulo
o al módulo actual, puede llamar a getModuleDirectory(),
opcionalmente pasar un nombre de módulo para conseguir el
directorio de ese módulo específico.
dispatch()dispatch(Zend_Controller_Request_Abstract $request = null,
Zend_Controller_Response_Abstract $response = null)
hace el trabajo pesado del front controller. Puede opcionalmente
tomar un request
object y/o un response object,
permitiendo al desarrollador pasar objetos peronalizados para
cada uno.
Si no se pasa ningun objeto solicitud o respuesta,
dispatch() comprobará por objetos previamente
registrados y utilizar esos o instanciar versiones por defecto
a utilizar en su proceso (en ambos casos, el sabor de HTTP será
utilizado por defecto).
Similarly, dispatch() checks for registered router and dispatcher
objects, instantiating the default versions of each if none is
found.
The dispatch process has three distinct events:
RoutingDispatchingResponse
Routing takes place exactly once, using the values in the
request object when dispatch() is called.
Dispatching takes place in a loop; a request may either indicate
multiple actions to dispatch, or the controller or a plugin may
reset the request object to force additional actions to
dispatch. When all is done, the front controller returns a
response.
run()Zend_Controller_Front::run($path) is a static
method taking simply a path to a directory containing
controllers. It fetches a front controller instance (via
getInstance(),
registers the path provided via setControllerDirectory(),
and finally dispatches.
Basically, run() is a convenience method that can
be used for site setups that do not require customization of the
front controller environment.
Environmental Accessor Methods
In addition to the methods listed above, there are a number of
accessor methods that can be used to affect the front controller
environment -- and thus the environment of the classes to which the
front controller delegates.
resetInstance() can be used to clear all
current settings. Its primary purpose is for testing, but it
can also be used for instances where you wish to chain
together multiple front controllers.
(set|get)DefaultControllerName() let you
specify a different name to use for the default controller
('index' is used otherwise) and retrieve the current value.
They proxy to the
dispatcher.
(set|get)DefaultAction() let you specify a
different name to use for the default action ('index' is
used otherwise) and retrieve the current value. They proxy
to the
dispatcher.
(set|get)Request() let you specify the request
class or object to use during the dispatch process and to
retrieve the current object. When setting the request
object, you may pass in a request class name, in which case
the method will load the class file and instantiate it.
(set|get)Router() let you specify the router
class or object to use during the dispatch process and to
retrieve the current object. When setting the router
object, you may pass in a router class name, in which case
the method will load the class file and instantiate it.
When retrieving the router object, it first checks to see if
one is present, and if not, instantiates the default router
(rewrite router).
(set|get)BaseUrl() let you specify the base
URL to strip when routing requests and to
retrieve the current value. The value is provided to the
request object just prior to routing.
(set|get)Dispatcher() let you specify the
dispatcher class or object to use during the
dispatch process and retrieve the current object. When
setting the dispatcher object, you may pass in a dispatcher
class name, in which case the method will load the class
file and instantiate it.
When retrieving the dispatcher object, it first checks to see if
one is present, and if not, instantiates the default
dispatcher.
(set|get)Response() let you specify the response
class or object to use during the dispatch process and to
retrieve the current object. When setting the response
object, you may pass in a response class name, in which case
the method will load the class file and instantiate it.
registerPlugin(Zend_Controller_Plugin_Abstract $plugin, $stackIndex = null)
allows you to register plugin objects.
By setting the optional $stackIndex, you can
control the order in which plugins will execute.
unregisterPlugin($plugin) let you
unregister plugin objects.
$plugin may be either a plugin object or a
string denoting the class of plugin to unregister.
throwExceptions($flag) is used to turn on/off
the ability to throw exceptions during the dispatch process.
By default, exceptions are caught and placed in the response
object; turning on throwExceptions()
will override this behaviour.
For more information, read .
returnResponse($flag) is used to tell the front
controller whether to return the response
(true) from dispatch(), or if the
response should be automatically emitted
(false). By default, the response is
automatically emitted (by calling
Zend_Controller_Response_Abstract::sendResponse());
turning on returnResponse() will override this
behaviour.
Reasons to return the response include a desire to check for
exceptions prior to emitting the response, needing to log
various aspects of the response (such as headers), etc.
Front Controller Parameters
In the introduction, we indicated that the front controller also
acts as a registry for the various controller components. It does so
through a family of "param" methods. These methods allow you to
register arbitrary data -- objects and variables -- with the front
controller to be retrieved at any time in the dispatch chain. These
values are passed on to the router, dispatcher, and action
controllers. The methods include:
setParam($name, $value) allows you to set a
single parameter of $name with value
$value.
setParams(array $params) allows you to set
multiple parameters at once using an associative array.
getParam($name) allows you to retrieve a single
parameter at a time, using $name as the
identifier.
getParams() allows you to retrieve the entire
list of parameters at once.
clearParams() allows you to clear a single
parameter (by passing a string identifier), multiple named
parameters (by passing an array of string identifiers), or the
entire parameter stack (by passing nothing).
There are several pre-defined parameters that may be set that have
specific uses in the dispatch chain:
useDefaultControllerAlways is used to hint to
the
dispatcher to use the default controller in the
default module for any request that is not dispatchable
(i.e., the module, controller, and/or action do not exist).
By default, this is off.
See
for more detailed information on using this setting.
disableOutputBuffering is used to hint to the
dispatcher that it should not use output
buffering to capture output generated by action controllers.
By default, the dispatcher captures any output and appends
it to the response object body content.
noViewRenderer is used to disable the ViewRenderer.
Set this parameter to true to disable it.
noErrorHandler is used to disable the Error
Handler plugin. Set this parameter to true to
disable it.
Extending the Front Controller
To extend the Front Controller, at the very minimum you will need
to override the getInstance() method:
Overriding the getInstance() method ensures that
subsequent calls to
Zend_Controller_Front::getInstance() will return an
instance of your new subclass instead of a
Zend_Controller_Front instance -- this is particularly
useful for some of the alternate routers and view helpers.
Typically, you will not need to subclass the front controller unless
you need to add new functionality (for instance, a plugin
autoloader, or a way to specify action helper paths). Some points
where you may want to alter behaviour may include modifying how
controller directories are stored, or what default router or
dispatcher are used.