Zend Framework Tutorial Action of the base class Zend_controller_action detailed, Controller base class
This article describes the base class zend_controller_action for the action of the Zend Framework tutorial. Share to everyone for your reference, as follows:
The realization of zend_controller_action
The Zend framework's action controller needs to inherit zend_controller_action,zend_controller_action to provide the basic functions of the action controller, referring to the following code:
Zend_controller_action_interface
<?phpinterface zend_controller_action_interface{/** * Class Constructor * * The request and Response objects sh Ould is registered with the * controller, as should is any additional optional arguments; These would be * available via {@link getrequest ()}, {@link getResponse ()}, and * {@link Getinvokeargs ()}, respectively . * * When overriding the constructor, please consider the "as a best * practice and ensure" is registere D appropriately; The easiest *-Simply call Parent::__construct ($request, $response, * $invokeArgs). * After the request, response, and Invokeargs am set, the * {@link $_helper helper broker} is initialized. * Finally, {@link init ()} is called as the final action of * instantiation, and could be safely overridden to perform initialization * tasks; As a general rule, override {@link init ()} instead of the * constructor to customize an action controller ' s Instantiatio N. * * @param Zend_contRoller_request_abstract $request * @param zend_controller_response_abstract $response * @param array $invokeArgs any A dditional invocation arguments * @return void */Public function __construct (zend_controller_request_abstract $reques T, zend_controller_response_abstract $response, array $invokeArgs = array ()); /** * Dispatch the requested action * * @param string $action Method name of action * @return void */Public fu Nction Dispatch ($action);}
zend_controller_action
<?phprequire_once ' zend/controller/action/helperbroker.php '; require_once ' zend/controller/action/ interface.php '; require_once ' zend/controller/front.php '; abstract class Zend_controller_action implements Zend_ controller_action_interface{protected $_classmethods; protected $_delimiters; Protected $_invokeargs = Array (); protected $_frontcontroller; protected $_request = null; protected $_response = null; Public $viewSuffix = ' phtml '; Public $view; protected $_helper = null; Public function __construct (zend_controller_request_abstract $request, Zend_controller_response_abstract $response, Array $invokeArgs = Array ()) {$this->setrequest ($request)->setresponse ($response)->_setinvokea RGS ($invokeArgs); $this->_helper = new Zend_controller_action_helperbroker ($this); $this->init (); Public Function init () {} public Function Initview () {if (! $this->getinvokearg (' noviewrenderer ') && $this->_helper->hashelper (' VIEWREnderer ') {return $this->view; } require_once ' zend/view/interface.php '; if (Isset ($this->view) && ($this->view instanceof zend_view_interface) {return $this->view; } $request = $this->getrequest (); $module = $request->getmodulename (); $dirs = $this->getfrontcontroller ()->getcontrollerdirectory (); if (Empty ($module) | |!isset ($dirs [$module]) {$module = $this->getfrontcontroller ()->getdispatcher ()->getd Efaultmodule (); } $baseDir = DirName ($dirs [$module]). Directory_separator. ' Views '; if (!file_exists ($baseDir) | |!is_dir ($BASEDIR)) {require_once ' zend/controller/exception.php '; throw new Zend_controller_exception (' Missing Base View directory (". $baseDir. '")'); } require_once ' zend/view.php '; $this->view = new Zend_view (Array (' basepath ' = $baseDir)); return $this->view; Public function render ($action = null, $name = NULL, $noController = False) { if (! $this->getinvokearg (' noviewrenderer ') && $this->_helper->hashelper (' Viewrenderer ')} {return $this->_helper->viewrenderer->render ($action, $name, $noController); } $view = $this->initview (); $script = $this->getviewscript ($action, $noController); $this->getresponse ()->appendbody ($view->render ($script), $name); Public Function Renderscript ($script, $name = null) {if (! $this->getinvokearg (' noviewrenderer ') && $thi S->_helper->hashelper (' Viewrenderer ')) {return $this->_helper->viewrenderer->renderscript ($script , $name); } $view = $this->initview (); $this->getresponse ()->appendbody ($view->render ($script), $name); Public Function getviewscript ($action = null, $noController = null) {if (! $this->getinvokearg (' Noviewrenderer ') && $this->_helper->hashelper (' Viewrenderer ') {$viewRenderer = $this->_helper-≫gethelper (' Viewrenderer '); if (null!== $noController) {$viewRenderer->setnocontroller ($noController); } return $viewRenderer->getviewscript ($action); } $request = $this->getrequest (); if (null = = = $action) {$action = $request->getactionname (); } elseif (!is_string ($action)) {require_once ' zend/controller/exception.php '; throw new Zend_controller_exception (' Invalid action specifier for View Render '); } if (null = = = $this->_delimiters) {$dispatcher = Zend_controller_front::getinstance ()->getdispatcher (); $wordDelimiters = $dispatcher->getworddelimiter (); $pathDelimiters = $dispatcher->getpathdelimiter (); $this->_delimiters = Array_unique (Array_merge ($wordDelimiters, (array) $pathDelimiters)); } $action = Str_replace ($this->_delimiters, '-', $action); $script = $action. '.' . $this->viewsuffix; if (! $noController) {$controller = $request->getcontrollernAme (); $controller = Str_replace ($this->_delimiters, '-', $controller); $script = $controller. Directory_separator. $script; } return $script; } public Function Getrequest () {return $this->_request; The Public Function setrequest (zend_controller_request_abstract $request) {$this->_request = $request; return $this; } public Function GetResponse () {return $this->_response; The Public Function setresponse (zend_controller_response_abstract $response) {$this->_response = $response; return $this; } protected function _setinvokeargs (array $args = Array ()) {$this->_invokeargs = $args; return $this; } public Function Getinvokeargs () {return $this->_invokeargs; The Public Function Getinvokearg ($key) {if (Isset ($this->_invokeargs[$key])) {return $this->_invokeargs[$k EY]; } return null; The Public Function Gethelper ($helperName) {return $this->_helper->{$helperName}; } public FUnction gethelpercopy ($helperName) {return clone $this->_helper->{$helperName}; The Public Function Setfrontcontroller (Zend_controller_front $front) {$this->_frontcontroller = $front; return $this; } public Function Getfrontcontroller () {//Used cache version if found if (null!== $this->_frontcontroller) { return $this->_frontcontroller; }//Grab singleton instance, if class has been loaded if (class_exists (' Zend_controller_front ')) {$this->_ Frontcontroller = Zend_controller_front::getinstance (); return $this->_frontcontroller; }//Throw exception in all other cases require_once ' zend/controller/exception.php '; throw new Zend_controller_exception (' Front Controller class have not been loaded '); Public Function Predispatch () {} public Function Postdispatch () {} public Function __call ($methodName, $args) {require_once ' zend/controller/action/exception.php '; if (' Action ' = = substr ($methodName,-6)) {$action = substr ($methodName, 0, strlen ($methodName)-6); throw new Zend_controller_action_exception (sprintf (' Action '%s ' does not exist and is not trapped in __call () ', $action), 404); } throw new Zend_controller_action_exception (sprintf (' Method '%s ' does not exist and is not trapped in __call () ', $met Hodname), 500); } Public Function Dispatch ($action) {//Notify helpers of Action Predispatch State $this->_HELPER->NOTIFYPR Edispatch (); $this->predispatch (); if ($this->getrequest ()->isdispatched ()) {if (null = = = $this->_classmethods) {$this->_classmetho ds = Get_class_methods ($this); }//If Pre-dispatch hooks introduced a redirect then stop dispatch//@see ZF-7496 If (! ( $this->getresponse ()->isredirect ()) {//Predispatch () didn ' t change the action, so we can continue I F ($this->getinvokearg (' usecasesensitiveactions ') | | In_array ($action, $this->_classmethods) {if ($this->getinvokearg (' usecasesensitiveactions ')) {trigger_error (' Using Case Sensitive Act Ions without word separators is deprecated; Please don't rely on this "feature"); } $this $action (); } else {$this->__call ($action, Array ()); }} $this->postdispatch (); }//Whats actually important here's this action controller is//shutting down, regardless of dispatching; Notify the helpers of this//state $this->_helper->notifypostdispatch (); Public function Run (zend_controller_request_abstract $request = null, zend_controller_response_abstract $response = Nu LL) {if (null!== $request) {$this->setrequest ($request); } else {$request = $this->getrequest (); } if (null!== $response) {$this->setresponse ($response); } $action = $request->getactionname (); if (empty ($action)) {$action = ' index '; } $action = $aCtion. ' Action '; $request->setdispatched (TRUE); $this->dispatch ($action); return $this->getresponse (); } protected function _getparam ($paramName, $default = null) {$value = $this->getrequest ()->getparam ($paramName ); if ((null = = = $value | | "= = = $value) && (null!== $default)) {$value = $default; } return $value; } protected function _setparam ($paramName, $value) {$this->getrequest ()->setparam ($paramName, $value); return $this; } protected function _hasparam ($paramName) {return null!== $this->getrequest ()->getparam ($paramName); } protected function _getallparams () {return $this->getrequest ()->getparams (); Final protected function _forward ($action, $controller = null, $module = NULL, array $params = null) {$request = $ This->getrequest (); if (null!== $params) {$request->setparams ($params); } if (null!== $controller) {$request->setcontrollername ($conTroller); Module should only is reset if controller has been specified if (null!== $module) {$request->setmodule Name ($module); }} $request->setactionname ($action)->setdispatched (false); } protected function _redirect ($url, array $options = Array ()) {$this->_helper->redirector->gotourl ($url, $ Options); }}
Zend_controller_action provides the render function for actions and views, as well as registration request and response objects, common helpers, and so on.
Common methods of motion controller
The methods and properties commonly used in the action controller are as follows:
$this->_helper mainly completes the assistant's related actions such as:
only the local controller; When the initialization is loaded, all actions on the controller are valid: $this->_helper->viewrenderer->setnorender (TRUE);//global: $this->_ Helper->removehelper (' Viewrenderer '); is also global, but requires collaboration with the local version to breed this controller: zend_controller_front::getinstance ()->setparam (' Noviewrenderer ', true);
By setting the Viewrenderer norender tag, you can simply disable parsing for a separate view (rendering):
Class Foocontroller extends zend_controller_action{public function baraction () { //disable Autorendering for the action only: $this->_helper->viewrenderer->setnorender (); }}
The main reason to prohibit viewrenderer is if you do not need a view object or if you do not pass the view script (for example, when using an action controller to service Web services protocols such as SOAP,XML-RPC or rest) to resolve. In most cases, you do not need to block viewrenderer globally, only selectively prohibit it in individual controllers or actions.
Related actions for request and response objects
Countless objects and variables are registered with the object, and each has accessor methods.
Request object: Getrequest () can be used to read the call action Request object.
Response object: GetResponse () can be used to read the response object that collects the final response. Some of the typical calls look like this:
$this->getresponse ()->setheader (' Content-type ', ' text/xml '); $this->getresponse ()->appendbody ($ content);
Invocation parameters: The front controller may pass parameters to the router, dispatcher, and action controller. In order to read these parameters, Getinvokearg ($key) can be used, and in addition, the entire parameter list is read with Getinvokeargs ().
Request parameters: Request an object phone request parameter, such as any _get or _post parameter, or specify the user parameter in the URL's path information. In order to read these parameters, you can use _getparam ($key) or _getallparams (). You can also use _setparam () to set the request parameters, which is useful when forwarding to a different action.
Use _hasparam ($key) to test whether a parameter exists (useful for logical branching).
Note: _getparam () can have an optional second parameter, and if it is not empty, it contains a default value. Use it to remove the call to _hasparam () before reading the value:
Use the default value of 1 if ID is not set$id = $this->_getparam (' id ', 1);//Instead Of:if ($this->_hasparam (' id ') { $id = $this->_getparam (' id ');} else { $id = 1;}
Related actions for views
Zend_controller_action provides a preliminary and flexible mechanism for view inheritance. There are two ways to do this: Initview () and render (); The former loosely loads the $view public property, which parses the view based on the action of the current request, which uses the directory hierarchy to determine the script path.
View Initialization
Initview () initializes the View object. In order to read the View object, render () calls Initview (), but it can be initialized at any time; By default, it uses the Zend_view object to assemble the $view property, but any class that implements Zend_view_interface can be used. If the $view has been initialized, it simply returns the property.
The default implementation uses the following hypothetical directory structure:
applicationormodule/
controllers/
indexcontroller.php
views/
scripts/
index/
Index.phtml
helpers/
filters/
In other words, the view script is assumed to be placed in the views/scripts/subdirectory, assuming that the views subdirectory also contains sibling features (helpers and filters). When determining the view script name and path, first use views/scripts/as the base path, and then add the directory named after the controller for the view script.
Parsing (Rendering) view
Render () has the following characteristics: The following signature:
String render (String $action = null, string $name = null, bool $noController = false);
Render () Parse view script. If no arguments are passed, it assumes that the requested script is [controller]/[action].phtml (. Phtml is the value of the $viewsuffix property). Pass a value for $action to parse the template in the [controller] subdirectory. To override with [controller], pass a true value to $nocontroller. Finally, the template is parsed to the response object, and if you want to parse to a named segment specified in the Response object, pass a value to $name.
Note: Because the Controller and action names may contain delimiters such as ' _ ', '. ' and '-', when deciding on the name of the view, render () normalizes them to '-'. Internally, it uses the word and path separators of the dispatcher to normalize. This way, the request to/foo.bar/baz-bat will parse the script foo-bar/baz-bat.phtml. If the action method contains camelcasing, remember that when the view script file name is determined, it becomes a '-' delimited word.
Some examples:
Class Mycontroller extends zend_controller_action{public function fooaction () { //renders my/foo.phtml $this->render (); Renders my/bar.phtml $this->render (' Bar '); Renders baz.phtml $this->render (' Baz ', NULL, true); Renders my/login.phtml to the ' form ' segment of the //Response Object $this->render (' Login ', ' form ');
//renders site.phtml to the ' page ' segment of the response //object; does not use the ' my/' subirectory $thi S->render (' site ', ' page ', true); } Public Function bazbataction () { //renders my/baz-bat.phtml $this->render ();} }
Other
_forward ($action, $controller = null, $module = NULL, array $params = NULL): Performs another action. If called in Predispatch (), the current requested action will be jumped over to support the new action. Otherwise, the action requested at _forward () is executed after the current action is processed.
_redirect ($url, array $options = Array ()): Redirect to another place. This method uses a URL and an optional set of options. By default, it performs an HTTP 302 redirect.
The options can include one or more of the following:
Exit: Exits immediately. If requested, it cleanly shuts down any open sessions and performs a redirect.
You can use the setredirectexit () accessor to set this option globally in the controller.
Prependbase: Whether to pre-consider the base URL and the URL provided by the request object to register together.
Use the setredirectprependbase () accessor to set this option globally in the controller.
Code: What HTTP code to use when redirecting. The default is 302; You can use any code from 301 to 306.
Use the Setredirectcode () accessor to set this option globally in the controller.
Extending the Custom Zend_controller_action
In order to create an action controller, the zend_controller_action must be inherited. At a minimum, you need to define the action methods that the controller may invoke.
In addition to creating useful functions for Web applications, you may find repeating the same setup and utility methods in different controllers, and if so, creating an inherited (extends) Zend_controller_action base class might solve the problem.
Example #1 How to handle non-existent actions
If the controller's request includes an undefined action method, Zend_controller_action::__call () is called. __call () is of course the Magic method used in PHP for overloading methods.
By default, this method throws a zend_controller_action_exception to indicate that the required method is not found in the controller. If the required method ends with ' action ', it is assumed that an action is requested and does not exist; Such an error results in an exception with code 404. All other methods result in an exception with code 500. This makes it easy for you to distinguish between a page not found or a program error in the error handle.
If you want to perform other operations, you should override this function. For example, if you want to display an error message, you can write it as follows:
Class Mycontroller extends zend_controller_action{public function __call ($method, $args) { if (' Action ' = = substr ($method,-6)) { //If The action method is not found, render the error //template return $this- Render (' error '); } All and methods throw an exception throw new Exception (' Invalid method ' . $method . ' "called '," ; }}
Another possibility is that you might want to forward to the default control page:
Class Mycontroller extends zend_controller_action{public function indexaction () { $this->render (); } Public function __call ($method, $args) { if (' Action ' = = substr ($method,-6)) { //If the action method is not found, forward to the //Index Action return $this->_forward (' index '); } All and methods throw an exception throw new Exception (' Invalid method ' . $method . ' "called '," ; }}
To customize the controller, in addition to rewriting __call (), the initialization, utilities, accessors, views, and dispatch hooks described earlier in this chapter can be overridden. As an example, if you save the View object to the registry, you might want to modify Initview () with the following code:
Abstract class My_base_controller extends zend_controller_action{public function Initview () { if (null = = = $this->view) { if (zend_registry::isregistered (' view ')) { $this->view = zend_registry::get (' view '); } else { $this->view = new Zend_view (); $this->view->setbasepath (DirName (__file__). '/.. /views '); } } return $this->view; }}
More interested in Zend related content readers can view the topic: "Zend framework of the introductory tutorial", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Tutorial", "PHP object-oriented Programming introduction tutorial "," Introduction to Php+mysql Database Operation "and" PHP common database Operation Skills Summary "
I hope this article is helpful to you in PHP programming.
Articles you may be interested in:
- Zend Framework Tutorial Autoloading Usage
- Examples of resource autoloading usages of the Zend framework tutorial
- Controller usage Analysis of MVC Framework for Zend Framework Tutorial
- Zend Framework Tutorial's routing function zend_controller_router detailed
- Zend Framework Tutorial Zend_controller_plugin plugin Usage
- Package Zend_controller_response Example of response object for Zend Framework tutorial
- Package Zend_controller_request example of request object for Zend Framework tutorial
- Zend Framework Tutorial Distributor Zend_controller_dispatcher Usage
- Zend Framework Tutorial Front Controller Zend_controller_front Usage
- Zend Framework Tutorial View component Zend_view Usage
- Zend Framework Tutorial Loader and Pluginloader usage
http://www.bkjia.com/PHPjc/1106893.html www.bkjia.com true http://www.bkjia.com/PHPjc/1106893.html techarticle Zend Framework Tutorial Action of the base class Zend_controller_action detailed, Controller base class This article describes the Zend Framework tutorial action of the base class Zend_controller_ Action. Share to the big ...