Zend Framework tutorial The action of the basic class Zend_controller_action detailed _php example

Source: Internet
Author: User
Tags constructor sprintf throw exception zend zend framework

This example describes the base class zend_controller_action of the actions of the Zend Framework tutorial. Share to everyone for your reference, specific as follows:

The realization of zend_controller_action

The Zend framework's action controller needs to inherit zend_controller_action,zend_controller_action provides the basic function of the action Controller, refer to the following code specifically:

Zend_controller_action_interface

<?php interface Zend_controller_action_interface {/** * Class constructor * * The request and response obj ECTS should is registered with the * controller, as should is any additional optional; These would be * available via {@link getrequest ()}, {@link GetResponse ()}, and * {@link Getinvokeargs ()}, respective
   Ly. * When overriding the constructor, please consider this usage as a best * practice and ensure, which is registe Red appropriately;
   The easiest * way to be to and simply call Parent::__construct ($request, $response, * $invokeArgs).
   * After the request, response, and Invokeargs are set, the * {@link $_helper helper broker} is initialized. * Finally, {@link init ()} is called as the final action of * instantiation, and may are safely overridden to perfor M initialization * tasks; As a, override {@link init ()} instead of the * constructor to customize a action controller ' s Instantiati
 On.  * * @param zend_controller_request_abstract $request * @param zend_controller_response_abstract $response * @pa Ram Array $invokeArgs Any additional invocation arguments * @return void */Public function __construct (zend_contr Oller_request_abstract $request, zend_controller_response_abstract $response, array $invok
  Eargs = Array ()); /** * Dispatch the requested action * * @param string $action method name of action * @return void */Pub
Lic function Dispatch ($action);

 }

zend_controller_action

<?php require_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)-&GT;_SETINV
    Okeargs ($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 ()->get
    Defaultmodule (); $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; The public function render ($action = null, $name = NULL, $noController = False) {if (! $this->getinvokearg (' noviewrenderer ') && $this-> _helper->hashelper (' Viewrenderer ') {return $this->_helper->viewrenderer->render ($action, $name, $noCo
    Ntroller);
    $view = $this->initview ();
    $script = $this->getviewscript ($action, $noController);
  $this->getresponse ()->appendbody ($view->render ($script), $name); The Public Function Renderscript ($script, $name = null) {if (! $this->getinvokearg (' Noviewrenderer ') && $ This->_helper->hashelper (' Viewrenderer ')) {return $this->_helper->viewrenderer->renderscript ($
    Script, $name);
    $view = $this->initview ();
  $this->getresponse ()->appendbody ($view->render ($script), $name); The Public function getviewscript ($action = null, $noController = null) {if (! $this->getinvokearg (' Noviewrendere R ') && $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;
  The Public Function getrequest () {return $this->_request;
    The Public Function setrequest (zend_controller_request_abstract $request) {$this->_request = $request;
  return $this;
  The 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;
  The Public Function Getinvokeargs () {return $this->_invokeargs; The Public Function Getinvokearg ($key) {if (Isset ($this->_invokeargs[$key))} {return $this->_invokeargs[$key];
  return null;
  The Public Function Gethelper ($helperName) {return $this->_helper->{$helperName};
  The Public Function gethelpercopy ($helperName) {return clone $this->_helper->{$helperName};
    The Public Function Setfrontcontroller (Zend_controller_front $front) {$this->_frontcontroller = $front;
  return $this; The Public Function Getfrontcontroller () {//Used cache version if found if (Null!== $this->_frontcontrolle
    R) {return $this->_frontcontroller; }//Grab singleton instance, if class has been loaded if (class_exists (' Zend_controller_front ')) {$this-&G
      T;_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 has not been loaded '); Public Function Predispatch () {} pubLic function Postdispatch () {} public Function __call ($methodName, $args) {require_once ' zend/controller/act
    Ion/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 () '), $me
  Thodname), 500); The Public Function Dispatch ($action) {//Notify Helpers's action Predispatch State $this->_helper->noti
    Fypredispatch ();
    $this->predispatch (); if ($this->getrequest ()->isdispatched ()) {if (null = = $this->_classmethods) {$this->_classmet
      Hods = Get_class_methods ($this); }//If Pre-dispatch Hooks introduced a redirect then stop dispatch//@see ZF-7496 If (!) ( $this->getresponse ()-&Gt;isredirect ())) {//Predispatch () didn ' t change the action, so we can continue if ($this->getinvokea RG (' usecasesensitiveactions ') | |
            In_array ($action, $this->_classmethods)) {if ($this->getinvokearg (' usecasesensitiveactions ')) { Trigger_error (' Using case sensitive the actions without word separators is deprecated;
          ');
        $this-> $action ();
        else {$this->__call ($action, Array ());
    }} $this->postdispatch (); }///whats actually important is the this action controller AM//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 ($paramN
     AME); 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 be reset if controller has been specified if (null!== $module) {$request->setmodu
      Lename ($module);
  }} $request->setactionname ($action)->setdispatched (false); protected function _redirect ($url, array $options = Array ()) {$this->_helper->redirector->gotourl ($url
  , $options);

 }
}

Zend_controller_action provides render features for actions and views, as well as registration requests and response objects, commonly used assistants, and so on.

Common methods of motion controller

The methods and properties commonly used in action controllers are as follows:

$this->_helper The main completion of the assistant's related operations such as:

is only a local controller; When the load is initialized, all actions for this controller are valid:
$this->_helper->viewrenderer->setnorender (true);
Global:
$this->_helper->removehelper (' viewrenderer ');
 is also global, but requires collaboration with the local version in order to reproduce 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 this action only:
    $this->_helper->viewrenderer->setnorender ();
  }


The main reason for banning viewrenderer is if you do not need view objects or if you do not use view scripts (for example, when using an action controller to serve a service agreement such as SOAP,XML-RPC or rest) to resolve. In most cases, you do not need to suppress viewrenderer globally, only selectively prohibit it in individual controllers or actions.

Request object and Response object related actions

Countless objects and variables are registered with the object, and each has accessor methods.

Request object: Getrequest () can be used to read the Invoke 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);

Call parameters: The front-end controller may pass parameters to the router, the dispatch device, and the action controller. To read these parameters, you can use Getinvokearg ($key) and read the entire argument list with Getinvokeargs ().

Request parameter: Requests the object handset request parameter, like any _get or _post parameter, or specifies the user parameter in the path information of the URL. To read these parameters, you can use either _getparam ($key) or _getallparams (). You can also use _setparam () to set request parameters, which is useful when forwarding to another action.

Use _hasparam ($key) to test whether a parameter exists (useful for logical branches).

Note: _getparam () can have an optional second argument, and if it is not empty, it contains a default value. Use it to eliminate calls to _hasparam () before the value is read:

Use default value of 1 if ID was 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 an initial, flexible mechanism for view inheritance. There are two ways to do this: Initview () and render (), which loosely load the $view public property, which resolves 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 () invokes Initview (), but it can be initialized at any time, by default, it assembles $view attributes with Zend_view objects, 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 functions (assistants and filters). When you determine the view script name and path, first use views/scripts/as the base path, and then add a directory named after the view script corresponding to the controller.

Parsing (Rendering) view

Render () has the following characteristics: has the following signature:

String render (String $action = null,
       string $name = null,
       bool $noController = false);

Render () parses the 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). Passing a value for $action will resolve the template in the [controller] subdirectory. To override with [controller], pass a true value to $nocontroller. Finally, the template is parsed into 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 the name of the view, render () normalizes them into '-'. Internally, it uses the word and path delimiters of the dispatch to normalize. In this way, the request to/foo.bar/baz-bat resolves the script foo-bar/baz-bat.phtml. If the action method contains camelcasing, remember that when you decide on the view script file name, it will become 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 with the ' my/' subirectory
    $th Is->render (' site ', ' page ', true);
  }
  Public Function bazbataction ()
  {
    //renders my/baz-bat.phtml
    $this->render ();
  }


Other

_forward ($action, $controller = null, $module = NULL, array $params = NULL): Perform another action. If invoked in Predispatch (), the current requested action will be jumped over to support the new action. Otherwise, the action requested at _forward () will be executed after the current action is processed.

_redirect ($url, array $options = Array ()): Redirect to another place. This method uses a URL and a set of optional options. By default, it performs an HTTP 302 redirect.

Options can include one or more of the following:

Exit: Exit now. If requested, it will cleanly close any open sessions and perform redirects.

You can set this option globally in the controller with the Setredirectexit () accessor.

Prependbase: Whether to register the underlying URL and the request object provided with the URL in advance.

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 a 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 might call.

In addition to creating useful functions for Web applications, you may find that the same settings and utility methods are duplicated in different controllers, and if so, creating an inherited (extends) Zend_controller_action base class might solve the problem.

Example #1 How to handle a nonexistent action

If the controller's request includes an undefined action method, Zend_controller_action::__call () will be invoked. __call () is of course the magic method used to overload the method in PHP.

By default, this method throws a zend_controller_action_exception to indicate that no required method is found in the controller. If the requested method ends with ' action ', assume that an action is requested and does not exist; Such an error results in an exception with code 404. All other methods cause an exception with code 500. This makes it easy to distinguish between errors in the error handle and whether the page is not found or is a program error.

If you want to perform other actions, you should rewrite this function. For example, if you want to display an error message, you can write as follows:

Class Mycontroller extends zend_controller_action
{public
  function __call ($method, $args)
  {
    if (' Action ' = = substr ($method,-6)) {
      //If The action method is found, render the error
      //template return
      $ This->render (' error ');
    }
    All other methods throw a 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 no T found, forward to the
      //Index action return
      $this->_forward (' index ');
    }
    All other methods throw a exception
    throw new Exception (' Invalid method ')
              . $method
              . ' called '
              ;
  }


In order to customize the controller, in addition to overriding __call (), methods such as initialization, utilities, accessors, views, and dispatch hooks mentioned earlier in this chapter can be overridden. As an example, if you save a view object to the registry, you might want to modify the Initview () using the code like the following:

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 site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.