In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use ViewRenderer, the Zend_Helpers action assistant of Zend Framework. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
The details are as follows:
Decoupling of view layer and controller in MVC structure, as well as rendering. Often repetitive or redundant work. If a complete framework, the use of MVC, will be a reasonable design of these operations. Allows developers to focus more on content rather than control the logical structure itself. In ZendFramework, this is done mainly through the action assistant ViewRenderer. ViewRenderer automatically completes the process of building and rendering view objects in the controller.
ViewRenderer
Introduction
The View parsing (ViewRenderer) assistant is designed to achieve the following goals:
There is no need to create an instance of the view object within the controller; the view object is automatically registered within the controller.
Automatically set the view script, helper, and filter path according to the current module. Assign the class name prefix of the current module named helper and filter class.
Create globally valid view objects for all distributed controllers and actions.
Allows developers to set default view resolution options for all controllers.
Add the ability to automatically parse the attempt script without intervention.
Allows developers to create their own specifications for view base paths and view script paths.
Note: if you manually execute _ forward (), redirect, or render, automatic parsing will not occur. Because when you perform these actions, you tell ViewRenderer that you have to determine the output for yourself.
Note: ViewRenderer Assistant is enabled by default.
You can disable the helper by using the noViewRenderer method of the front controller, setting parameters ($front- > setParam ('noViewRenderer', true)), or removing the helper (Zend_Controller_Action_HelperBroker::removeHelper (' viewRenderer')) from the assistant broker stack (helper broker stack).
If you want to modify the ViewRenderer settings before distributing the front-end controller, you can use the following two methods:
Create an instance and register your own ViewRenderer object, then pass it to the assistant broker.
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer (); $viewRenderer- > setView ($view)-> setViewSuffix ('php'); Zend_Controller_Action_HelperBroker::addHelper ($viewRenderer)
Initialize and / or get the ViewRenderer object immediately through the assistant broker.
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper ('viewRenderer'); $viewRenderer- > setView ($view)-> setViewSuffix (' php')
API
In most cases, you simply create a ViewRenderer object and pass it to the action assistant broker. The easiest way to create an instance and register is to use the assistant broker's getStaticHelper () method:
Zend_Controller_Action_HelperBroker::getStaticHelper ('viewRenderer')
When the action controller is first instantiated, it triggers ViewRenderer to create a view object. Each instantiation of the action controller calls the init () method of ViewRenderer, sets the view properties of the action controller, and calls the addScriptPath () method with a class prefix parameter named after the current module, which is valid for all helper and filter classes defined for the module. (this will be called with a class prefix named after the current module, effectively namespacing all helper and filter classes you define for the module. )
Each time the postDispatch () method is executed, it executes the render () method for the current action.
For example, this class:
/ / A controller class, foo module:class Foo_BarController extends Zend_Controller_Action {/ / Render bar/index.phtml by default; no action required public function indexAction () {} / / Render bar/populate.phtml with variable 'foo' set to' bar'. / / Since view object defined at preDispatch (), it's already available. Public function populateAction () {$this- > view- > foo = 'bar';}}. / / in one of your view scripts:$this- > foo (); / / call Foo_View_Helper_Foo::foo ()
ViewRenderer also defines a number of accessors for setting and fetching view options.
SetView ($view) sets the view object for ViewRenderer. Get the set value with the public class property $view.
SetNeverRender ($flag = true) enables or disables automatic parsing globally, that is, it works for all controllers. If set to true, postDispatch () will not automatically call render () within all controllers. GetNeverRender () returns the current set value.
SetNoRender ($flag = true) is used to enable or disable automatic parsing, and if set to true, postDispatch () does not call the render () method within the current controller. This setting is reset every time preDispatch () is executed. GetNoRender () returns the current set value.
SetNoController ($flag = true) tells render () not to look for view scripts in a subdirectory named after the controller. GetNoController () returns the current value.
SetNeverController ($flag = true) is similar to setNoController ($flag = true), but it is valid globally-- that is, it is not reset every time an action is distributed. GetNeverController () returns the current value.
SetScriptAction ($name) is used to specify the view script to parse. Name is the name of the script without the suffix (without the controller subdirectory, unless noController is turned on). If not specified, it looks for a view script named after the action in the request object. GetScriptAction () returns the current value.
SetResponseSegment ($name) is used to specify which named fragment in the response object to resolve to. If not specified, resolve to the default fragment. GetResponseSegment () returns the current value.
InitView ($path, $prefix, $options) can specify the base path of the view, set class prefixes for helper and filter scripts, and set ViewRenderer options. You can pass in any of the following flags: neverRender,noRender,noController, scriptAction, and responseSegment.
SetRender ($action = null, $name = null, $noController = false) can set scriptAction, responseSegment, and noController at once. Direct () is its alias, which makes it easy to call in the controller.
/ / Render 'foo' instead of current action script$this- > _ helper- > viewRenderer (' foo'); / / render form.phtml to the 'html' response segment, without using a helper- / controller viewscript subdirectory:$this- > _ helper- > viewRenderer (' form', 'html', true)
Note: setRender () and direct () don't actually parse the view script, but prompt postDispatch () and postDispatch () to parse the view.
The constructor allows optional incoming parameter view objects and ViewRenderer options, and accepts the same flag (flags) as initView ():
$view = new Zend_View (array ('encoding' = >' UTF-8')); $options = array ('noController' = > true,' neverRender' = > true); $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer ($view, $options)
There are several additional methods for customizing path rules, determining view base paths to add view objects, and determining view script paths to find and parse view scripts. Each of these methods has one or more placeholders (placehodlers) below.
: moduleDir refers to the base directory of the current module (typically the parent directory of the module's controller directory).
: module references the current module name.
: controller references the current controller name.
: action references the current module name.
: suffix refers to the current view script suffix (which can be set through setViewSuffix ()).
Methods related to controller path rules:
SetViewBasePathSpec ($spec) can change the path rules that determine the base path added to the view object. The default rule is moduleDir/views. You can use getViewBasePathSpec () to get the current rule at any time.
SetViewScriptPathSpec ($spec) allows you to change the path rules that determine the path to a separate view script (excluding the attempt script base path). The default path rule is: controller/:action.:suffix. The current rule can be obtained at any time through getViewScriptPathSpec ().
SetViewScriptPathNoControllerSpec ($spec) allows you to change the path rules that determine the path to a separate view script path (excluding the attempt script base path) when the noController is in effect. The default rule is action.:suffix, and the current rule can be obtained at any time through getViewScriptPathNoControllerSpec ().
For well-designed controls on top of the path specification, Zend_Filter_Inflector can be used. In depth, the view parser (ViewRenderer) has used inflector to perform path mapping. To interact with inflector-either set your own or modify the default inflector, the following methods can be used:
GetInflector () will get the inflector. If it does not exist in the view parser, it creates one with the default rules.
By default, it uses static rule references and static targets as suffixes and module directories; this allows different view parsers to have the ability to dynamically modify inflector properties.
SetInflector ($inflector, $reference) allows you to set custom inflector to use with the view parser. If $reference is true, it sets the suffix and module directory as static references and targets to the view parser properties.
Note: default lookup convention (Conventions)
The view parser does some path standardization to make it easier for view scripts to find. The default rules are as follows:
: module: mixed words and hump words are separated by a dash and the whole string is turned into lowercase. For example, "FooBarBaz" becomes "foo-bar-baz".
Internally, Deformers (inflector) use filters Zend_Filter_Word_CamelCaseToDash and Zend_Filter_StringToLower.
: controller: mixed words and hump words are separated by dashes; underscores are converted to directory delimiters, and the whole string is lowercase. For example: "FooBar" becomes "foo-bar"; "FooBar_Admin" becomes "foo-bar/admin".
Internally, inflector uses filters Zend_Filter_Word_CamelCaseToDash, Zend_Filter_Word_UnderscoreToSeparator, and Zend_Filter_StringToLower.
Action: mixed words and hump words are separated by dashes; non-alphanumeric characters are translated into dashes and the whole string is lowercase. For example, "fooBar" becomes "foo-bar"; "foo-barBaz" becomes "foo-bar-baz".
Internally, inflector uses filters Zend_Filter_Word_CamelCaseToDash, Zend_Filter_PregReplace, and Zend_Filter_StringToLower.
The last item in the view parser API is about actually determining the view script path and parsing the view. These include:
RenderScript ($script, $name) allows you to parse scripts for specified paths, optionally named path fragments. (renderScript ($script, $name) allows you to render a script with a path you specify, optionally to a named path segment. When using this method, ViewRenderer does not automatically determine the script name, but instead passes the $script parameter directly to the render () of the view object.
Note: when the view has been parsed to the response object, noRender will be set to prevent the same script from being parsed multiple times.
Note: by default, Zend_Controller_Action::renderScript () proxies the renderScript () method of ViewRenderer.
GetViewScript ($action, $vars) creates a path to the view script based on the incoming action and / or variables in $vars. The keys in this array can contain all the path-specified keys ('moduleDir','module',' controller', 'action', and' suffix'). Any variables passed in will be used first, otherwise the value based on the current request will be used.
GetViewScript () uses viewScriptPathSpec or viewScriptPathNoControllerSpec based on the value set by the noController flag.
The word delimiter in the module, controller, and action is replaced by a short line ('-'). Therefore, the controller name 'foo.bar' and actions' baz:bat' will get the view script path 'foo-bar/baz-bat.phtml' according to the default path rules.
Note: by default, Zend_Controller_Action::getViewScript () proxies the getViewScript () method of ViewRenderer.
Render ($action, $name, $noController) first checks whether the $name or $noController parameter is passed, and if so, sets the corresponding flag in the ViewRenderer (response fragment and noController, respectively). Then pass the $action parameter to getViewScript (), and finally pass in the calculated attempt script path to renderScript ().
Note: note the marginal effect of using render (): the incoming response fragment name and noController flag are persisted in the view object. In addition, noRender will be set after parsing.
Note: by default, Zend_Controller_Action::render () proxies the render () method of ViewRenderer.
RenderBySpec ($action, $vars, $name) allows you to pass in path rule variables to determine the path of the view script that is created. It passes $action and $vars to getScriptPath (), and the script path result and $name to renderScript ().
Basic usage example
Basic usage of Example # 9
In most basic use, simply initialize and register the ViewRenderer helper using the helper broker in bootstrap, and then set the variable in the action method.
/ / In your bootstrap:Zend_Controller_Action_HelperBroker::getStaticHelper ('viewRenderer');. / /' foo' module, 'bar' controller:class Foo_BarController extends Zend_Controller_Action {/ / Render bar/index.phtml by default; no action required public function indexAction () {} / / Render bar/populate.phtml with variable' foo' set to 'bar'. / / Since view object defined at preDispatch (), it's already available. Public function populateAction () {$this- > view- > foo = 'bar';} / / Renders nothing as it forwards to another action; the new action / / will perform any rendering public function bazAction () {$this- > _ forward (' index');} / / Renders nothing as it redirects to another location public function batAction () {$this- > _ redirect ('/ index');}}
Note: naming rules: word delimiters in controller and action names
If the controller or action name consists of several words, the dispatcher requires that the URL be separated by a specific path and word delimiter. When ViewRenderer creates a path, it replaces any path delimiter in the controller name with the actual path delimiter ('/'), and any word delimiter with a short line ('-'). The call to action / foo.bar/baz.bat is distributed to FooBarController::bazBatAction () in FooBarController.php, then the call to action / bar_baz/baz-bat by parsing foo-bar/baz-bat.phtml; is distributed to Bar_BazController::bazBatAction () in Bar/BazController.php, and the bar/baz/baz-bat.phtml is parsed.
Notice that in the second example, the module is still the default module, but because of the path delimiter, the controller receives the name Bar_BazController, which is in the file Bar/BazController.php. ViewRenderer simulates the directory layering of the controller.
Example # 10 disable automatic parsing
For some actions and controllers, you may want to turn off automatic parsing-for example, if you want to send other types of output (XML,JSON, etc.), or simply don't want to send anything. There are two options: turn off all automatic parsing (setNeverRender ()), or just turn off automatic parsing for the current action (setNoRender ()).
/ / Baz controller class, bar module:class Bar_BazController extends Zend_Controller_Action {public function fooAction () {/ / Don't auto render this action $this- > _ helper- > viewRenderer- > setNoRender ();}} / / Bat controller class, bar module:class Bar_BatController extends Zend_Controller_Action {public function preDispatch () {/ / Never auto render this controller's actions $this- > _ helper- > viewRenderer- > setNoRender ();}}
Note: in most cases, turning off automatic parsing (setNeverRender ()) globally makes no sense, because the only thing ViewRenderer does is set the view object automatically.
Example # 11 choose a different view script
In some cases, you need to parse another script instead of a script named after an action. For example, if you have a controller that contains both add and edit actions, they may both display the same 'form' view, although they have different value set sets. Simply change the name of the script using setScriptAction () or setRender (), or call the helper as a member method, which will call setRender ().
/ / Bar controller class, foo module:class Foo_BarController extends Zend_Controller_Action {public function addAction () {/ / Render 'bar/form.phtml' instead of' bar/add.phtml' $this- > _ helper- > viewRenderer ('form');} public function editAction () {/ / Render' bar/form.phtml' instead of 'bar/edit.phtml' $this- > _ helper- > viewRenderer- > setScriptAction (' form');} public function processAction () {/ / do some validation... If (! $valid) {/ / Render 'bar/form.phtml' instead of' bar/process.phtml' $this- > _ helper- > viewRenderer- > setRender ('form'); return;} / / otherwise continue processing... }}
Example # 12 modify registered View Modifying the registered view
What if you need to modify the view object-such as changing the helper path or coding? You can modify the view object settings in the controller, or grab the view object from the ViewRenderer; both refer to the same object.
/ / Bar controller class, foo module:class Foo_BarController extends Zend_Controller_Action {public function preDispatch () {/ / change view encoding $this- > view- > setEncoding ('UTF-8');} public function bazAction () {/ / Get view object and set escape callback to' htmlspecialchars' $view = $this- > _ helper- > viewRenderer- > view; $view- > setEscape ('htmlspecialchars');}}
Examples of advanced usage
Example # 13 modify path rules
In some cases, the default path rules may not suit the needs of the site. For example, you want to have a separate template tree that designers can access (for example, if you use »Smarty, this is a typical case). In this case, you may want to hard-code the base path rules of the view, creating a set of rules for the action view script path itself.
Assume that the base path of the view is'/ opt/vendor/templates', wants to reference the view script through': moduleDir/:controller/:action.:suffix'; if you set the noController flag, you want to resolve it at the top level rather than in a subdirectory (': action.:suffix'). Eventually you want to use 'tpl' as the suffix for the view script file.
/ * * In your bootstrap: * / Different view implementation$view = new ZF_Smarty (); $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer ($view); $viewRenderer- > setViewBasePathSpec ('/ opt/vendor/templates')-> setViewScriptPathSpec (': module/:controller/:action.:suffix')-> setViewScriptPathNoControllerSpec (': action.:suffix')-> setViewSuffix ('tpl'); Zend_Controller_Action_HelperBroker::addHelper ($viewRenderer)
Example # 14 parsing multiple view scripts in one action
Sometimes you may need to parse multiple view scripts in a single action. This is very simple, just call render () multiple times:
Class SearchController extends Zend_Controller_Action {public function resultsAction () {/ / Assume $this- > model is the current model $this- > view- > results = $this- > model- > find ($this- > _ getParam ('query','); / / render () by default proxies to the ViewRenderer / / Render first the search form and then the results $this- > render ('form'); $this- > render (' results');} public function formAction () {/ do nothing; ViewRenderer autorenders the viewscript}}
The relevant source codes of ViewRenderer are as follows. After careful analysis, it is not difficult to see the implementation method:
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.