Migración de versiones anteriores La API de los componentes de MVC ha cambiado en el tiempo. Si usted ha empezado a usar una versión anterior de Zend Framework, sigua la guía de abajo para migrar sus acripts para usar la arquitectura nueva. Migración de 1.6.x a 1.7.0 o nuevas versiones El despachador de la interfaz cambios Los usuarios llamaron nuestra atención el hecho de que Zend_Controller_Action_Helper_ViewRenderer estaba utilizando un método despachador de la clase abstracta que no está en el despachador de la interfaz. Hemos añadido el siguiente método para garantizar que los despachadores de costumbre seguirán trabajando con las implementaciones enviadas: formatModuleName(): debe utilizarse para tomar un nuevo nombre de controlador, tal como uno que deberia estar basado dentro de una petición objeto, y cambiarlo a un nombre de clase apropiado que la clase extendida Zend_Controller_Action deberia usar Migrando desde 1.5.x to 1.6.0 o versiones posteriores El Despachador de la Interfaz de cambios Los usuarios atrajeron nuestra atención con el hecho de que Zend_Controller_Front y Zend_Controller_Router_Route_Module fueron utilizando métodos del despachador que no estaban en la interfaz del despachador. Ahora hemos adicionado los siguientes tres métodos para asegurar que los despachadores diseñados sigan trabajando con las implementaciones enviadas: getDefaultModule(): debe retornar el nombre del módulo por defecto. getDefaultControllerName(): debe retornar el nombre del controlador por defecto. getDefaultAction(): debe retornar el nombre de la acción por defecto. Migranado desde 1.0.x a 1.5.0 o versiones posteriores Aunque la mayoría de la funcionalidad básica sigue siendo la misma, y todas las funcionalidades documentadas siguen siendo la mismas, hay una en particular "característica" undocumented que ha cambiado. Al escribir las URLs, la manera de escribir la documentada acción camelCased es usar un separador de palabra, que son "." o '-' por defecto, pero pueden ser configurados en el despachador. El despachador internamente convierte en minúsculas el nombre de la acción, y usa estos separadores de palabra para volver a montar el método de la acción camelCasing. Sin embargo, debido a que las funciones de PHP no son sensibles a mayúsculas y minúsculas, usted podría escribir las URLs usando camelCasing, y el despachador los devolvería a la misma ubicación. Por ejemplo, 'camel-cased' se convertirá en 'camelCasedAction' por el despachador, mientras que 'camelCased' se convertiría en 'camelCasedAction'; sin embargo, debido a la insensibilidad de PHP, ambos ejecutarán el mismo método. Esto causa problemas con la vista ViewRenderer cuando devuelve scripts de la vista. El canónico, la documentada forma es que todos los separadores de palabra se conviertan en guiones, y las palabras en minúsculas. Esto crea un lazo semántico entre las acciones y los scripts de las vistas, y la normalización asegura que los scripts puedan ser encontrados. Sin embargo, si la acción "camelCased' es llamada y de hecho retornada, el separador de la palabra no está mas presente, y los ViewRenderer intenta devolver a una ubicación diferente -- 'camelcased.phtml' en vez de 'camel-cased.phtml'. Algunos desarrolladores se basarón en esta "característica", que nunca fue la intención. Varios cambios en el árbol 1.5.0 , sin embargo, hizo que la vista ViewRenderer ya no resuelva estas direcciones, la semántica esta ahora forzada. La primera de ellas, el despachador ahora impone la sensibilidad en los nombres de la acción. Lo que esto significa es que la referencia a sus acciones en la url utilisando camelCasing ya no para devolver al mismo método que utilizan los separadores de palabras (es decir, 'camel-casing'). Esto nos lleva a la vista ViewRenderer ahora sólo en honor a las acciones palabra-separador cuando se devuleven los scripts vista. Si usted nota que estaba dependiendo en esta "caracteristica", usted tiene muchas opciones: Mejor opción: cambiar el nombre de sus scripts de la vistas. Pros: compatibilidad hacia adelante. Contras: si usted tiene muchos scripts vista que se basan en la primera vista, una conducta no deseada, tendrá mucho por hacer. Segunda mejor opción: La vista ViewRenderer delega ahora resoluciones de scripts de vistas a Zend_Filter_Inflector ; se puede modificar las normas del inflector para que ya no separe las palabras de una acción con un guión: getInflector(); $inflector->setFilterRule(':action', array( new Zend_Filter_PregReplace( '#[^a-z0-9' . preg_quote(DIRECTORY_SEPARATOR, '#') . ']+#i', '' ), 'StringToLower' )); ]]> El anterior código modificará el inflector para que ya no separe las palabras con guión, usted puede querer eliminar el filtro 'StringToLower' si usted deseahacer el nombre de script de vista actual camelCased también. Si cambiar el nombre del script vista sería demasiado tedioso o tiempo consumido, esta es su mejor opción hasta que pueda encontrar el tiempo para hacerlo. La opción menos deseable: Usted puede forzar al despachador para despachar nombres de acción camelCased con un nuevo controlador bandera, 'useCaseSensitiveActions': setParam('useCaseSensitiveActions', true); ]]> Esto le permitirá utilizar camelCasing sobre la url y siguir tieniendo resuelta la misma acción como cuando se utilizaba los separadores de palabra. Sin embargo, esto significa que los problemas originales se iran terminando, lo más probable es utilizar la segunda opción anterior, además de esto para que las cosas funcionen confiablemente en todo. Note, también, el uso de esta bandera aumentará un aviso de que este uso es obsoleto. Migrando desde 0.9.3 a 1.0.0RC1 o versiones posteriores Los cambios principales introducidos en 1.0.0RC1 son la introducción de y la activación por defecto del plugin ErrorHandler y de acción ayuda ViewRenderer Por favor, lea la documentación de cada uno completamente para ver cómo funcionan y qué efecto pueden tener en sus aplicaciones. El plugin ErrorHandler corre durante postDispatch () para el control de excepciones, y enviarlo a un especifico controlador de errores. Usted debe incluir tal controlador en su aplicación. Usted puede desactivarlo determinando el parámetro del controlador noErrorHandler : setParam('noErrorHandler', true); ]]> La acción de ayuda ViewRenderer automatiza inyección de vistas en controladores de acción así como los autogeneradores de scripts de vistas basados en la acción actual. El principal problema que se puede encontrar es si se tiene acciones que no generan scripts de vista y tampoco llevan o redireccionan, como ViewRenderer intentará generar un scrip de vista basado en el nombre de la acción. There are several strategies you can take to update your code. In the short term, you can globally disable the ViewRenderer in your front controller bootstrap prior to dispatching: setParam('noViewRenderer', true); ]]> However, this is not a good long term strategy, as it means most likely you'll be writing more code. When you're ready to start using the ViewRenderer functionality, there are several things to look for in your controller code. First, look at your action methods (the methods ending in 'Action'), and determine what each is doing. If none of the following is happening, you'll need to make changes: Calls to $this->render() Calls to $this->_forward() Calls to $this->_redirect() Calls to the Redirector action helper The easiest change is to disable auto-rendering for that method: _helper->viewRenderer->setNoRender(); ]]> If you find that none of your action methods are rendering, forwarding, or redirecting, you will likely want to put the above line in your preDispatch() or init() methods: _helper->viewRenderer->setNoRender() // .. do other things... } ]]> If you are calling render(), and you're using the Conventional Modular directory structure, you'll want to change your code to make use of autorendering: If you're rendering multiple view scripts in a single action, you don't need to change a thing. If you're simply calling render() with no arguments, you can remove such lines. If you're calling render() with arguments, and not doing any processing afterwards or rendering multiple view scripts, you can change these calls to read $this->_helper->viewRenderer(). If you're not using the conventional modular directory structure, there are a variety of methods for setting the view base path and script path specifications so that you can make use of the ViewRenderer. Please read the ViewRenderer documentation for information on these methods. If you're using a view object from the registry, or customizing your view object, or using a different view implementation, you'll want to inject the ViewRenderer with this object. This can be done easily at any time. Prior to dispatching a front controller instance: Any time during the bootstrap process: setView($view); ]]> There are many ways to modify the ViewRenderer, including setting a different view script to render, specifying replacements for all replaceable elements of a view script path (including the suffix), choosing a response named segment to utilize, and more. If you aren't using the conventional modular directory structure, you can even associate different path specifications with the ViewRenderer. We encourage you to adapt your code to use the ErrorHandler and ViewRenderer as they are now core functionality. Migrating from 0.9.2 to 0.9.3 or Newer 0.9.3 introduces action helpers. As part of this change, the following methods have been removed as they are now encapsulated in the redirector action helper: setRedirectCode(); use Zend_Controller_Action_Helper_Redirector::setCode(). setRedirectPrependBase(); use Zend_Controller_Action_Helper_Redirector::setPrependBase(). setRedirectExit(); use Zend_Controller_Action_Helper_Redirector::setExit(). Read the action helpers documentation for more information on how to retrieve and manipulate helper objects, and the redirector helper documentation for more information on setting redirect options (as well as alternate methods for redirecting). Migrating from 0.6.0 to 0.8.0 or Newer Per previous changes, the most basic usage of the MVC components remains the same: However, the directory structure underwent an overhaul, several components were removed, and several others either renamed or added. Changes include: Zend_Controller_Router was removed in favor of the rewrite router. Zend_Controller_RewriteRouter was renamed to Zend_Controller_Router_Rewrite, and promoted to the standard router shipped with the framework; Zend_Controller_Front will use it by default if no other router is supplied. A new route class for use with the rewrite router was introduced, Zend_Controller_Router_Route_Module; it covers the default route used by the MVC, and has support for controller modules. Zend_Controller_Router_StaticRoute was renamed to Zend_Controller_Router_Route_Static. Zend_Controller_Dispatcher was renamed Zend_Controller_Dispatcher_Standard. Zend_Controller_Action::_forward()'s arguments have changed. The signature is now: $action is always required; if no controller is specified, an action in the current controller is assumed. $module is always ignored unless $controller is specified. Finally, any $params provided will be appended to the request object. If you do not require the controller or module, but still need to pass parameters, simply specify null for those values. Migrating from 0.2.0 or before to 0.6.0 The most basic usage of the MVC components has not changed; you can still do each of the following: addRoute('user', 'user/:username', array('controller' => 'user', 'action' => 'info') ); /* -- set it in a controller -- */ $ctrl = Zend_Controller_Front::getInstance(); $ctrl->setRouter($router); /* -- set controller directory and dispatch -- */ $ctrl->setControllerDirectory('/path/to/controllers'); $ctrl->dispatch(); ]]> We encourage use of the Response object to aggregate content and headers. This will allow for more flexible output format switching (for instance, JSON or XML instead of XHTML) in your applications. By default, dispatch() will render the response, sending both headers and rendering any content. You may also have the front controller return the response using returnResponse(), and then render the response using your own logic. A future version of the front controller may enforce use of the response object via output buffering. There are many additional features that extend the existing API, and these are noted in the documentation. The main changes you will need to be aware of will be found when subclassing the various components. Key amongst these are: Zend_Controller_Front::dispatch() by default traps exceptions in the response object, and does not render them, in order to prevent sensitive system information from being rendered. You can override this in several ways: Set throwExceptions() in the front controller: throwExceptions(true); ]]> Set renderExceptions() in the response object: renderExceptions(true); $front->setResponse($response); $front->dispatch(); // or: $front->returnResponse(true); $response = $front->dispatch(); $response->renderExceptions(true); echo $response; ]]> Zend_Controller_Dispatcher_Interface::dispatch() now accepts and returns a object instead of a dispatcher token. Zend_Controller_Router_Interface::route() now accepts and returns a object instead of a dispatcher token. Zend_Controller_Action changes include: The constructor now accepts exactly three arguments, Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, and array $params (optional). Zend_Controller_Action::__construct() uses these to set the request, response, and invokeArgs properties of the object, and if overriding the constructor, you should do so as well. Better yet, use the init() method to do any instance configuration, as this method is called as the final action of the constructor. run() is no longer defined as final, but is also no longer used by the front controller; its sole purpose is for using the class as a page controller. It now takes two optional arguments, a Zend_Controller_Request_Abstract $request and a Zend_Controller_Response_Abstract $response. indexAction() no longer needs to be defined, but is encouraged as the default action. This allows using the RewriteRouter and action controllers to specify different default action methods. __call() should be overridden to handle any undefined actions automatically. _redirect() now takes an optional second argument, the HTTP code to return with the redirect, and an optional third argument, $prependBase, that can indicate that the base URL registered with the request object should be prepended to the url specified. The _action property is no longer set. This property was a Zend_Controller_Dispatcher_Token, which no longer exists in the current incarnation. The sole purpose of the token was to provide information about the requested controller, action, and URL parameters. This information is now available in the request object, and can be accessed as follows: _action->getControllerName(). // The example below uses getRequest(), though you may also directly // access the $_request property; using getRequest() is recommended as // a parent class may override access to the request object. $controller = $this->getRequest()->getControllerName(); // Retrieve the requested action name // Access used to be via: $this->_action->getActionName(). $action = $this->getRequest()->getActionName(); // Retrieve the request parameters // This hasn't changed; the _getParams() and _getParam() methods simply // proxy to the request object now. $params = $this->_getParams(); // request 'foo' parameter, using 'default' as default value if not found $foo = $this->_getParam('foo', 'default'); ]]> noRouteAction() has been removed. The appropriate way to handle non-existent action methods should you wish to route them to a default action is using __call(): defaultAction(); } throw new Zend_Controller_Exception('Invalid method called'); } ]]> Zend_Controller_RewriteRouter::setRewriteBase() has been removed. Use Zend_Controller_Front::setBaseUrl() instead (or Zend_Controller_Request_Http::setBaseUrl(), if using that request class). Zend_Controller_Plugin_Interface was replaced by Zend_Controller_Plugin_Abstract. All methods now accept and return a object instead of a dispatcher token.