7.7. Action Controllers

7.7.1. Introduction

Zend_Controller_Action is an abstract class you may use for implementing Action Controllers for use with the Front Controller when building a website based on the Model-View-Controller (MVC) pattern.

To use Zend_Controller_Action, you will need to subclass it in your actual action controller classes (or subclass it to create your own base class for action controllers). The most basic operation is to subclass it, and create action methods that correspond to the various actions you wish the controller to handle for your site. Zend_Controller's routing and dispatch handling will autodiscover any methods ending in 'Action' in your class as potential controller actions.

For example, let's say your class is defined as follows:

class FooController extends Zend_Controller_Action
{
    public function barAction()
    {
        // do something
    }

    public function bazAction()
    {
        // do something
    }
}

The above FooController class (controller foo) defines two actions, bar and baz.

There's much more that can be accomplished than this, such as custom initialization actions, default actions to call should no action (or an invalid action) be specified, pre- and post-dispatch hooks, and a variety of helper methods. This chapter serves as an overview of the action controller functionality

7.7.2. Object initialization

While you can always override the action controller's constructor, we do not recommend this. Zend_Controller_Action::__construct() performs some important tasks, such as registering the request and response objects, as well as any custom invocation arguments passed in from the front controller. If you must override the constructor, be sure to call parent::__construct($request, $response, $invokeArgs).

The more appropriate way to customize instantiation is to use the init() method, which is called as the last task of __construct(). For example, if you want to connect to a database at instantiation:

class FooController extends Zend_Controller_Action
{
    public function init()
    {
        $this->db = Zend_Db::factory('Pdo_Mysql', array(
            'host'     => 'myhost',
            'username' => 'user',
            'password' => 'XXXXXXX',
            'dbname'   => 'website'
        ));
    }
}

7.7.3. Pre- and Post-Dispatch Hooks

Zend_Controller_Action specifies two methods that may be called to bookend a requested action, preDispatch() and postDispatch(). These can be useful in a variety of ways: verifying authentication and ACLs prior to running an action (by calling _forward() in preDispatch(), the action will be skipped), for instance, or placing generated content in a sitewide template (postDispatch()).

7.7.4. Accessors

A number of objects and variables are registered with the object, and each has accessor methods.

  • Request Object: getRequest() may be used to retrieve the request object used to call the action.

  • Response Object: getResponse() may be used to retrieve the response object aggregating the final response. Some typical calls might look like:

    $this->getResponse()->setHeader('Content-Type', 'text/xml');
    $this->getResponse()->appendBody($content);
    
  • Invocation Arguments: the front controller may push parameters into the router, dispatcher, and action controller. To retrieve these, use getInvokeArg($key); alternatively, fetch the entire list using getInvokeArgs().

  • Request parameters: The request object aggregates request parameters, such as any _GET or _POST parameters, or user parameters specified in the URL's path information. To retrieve these, use _getParam($key) or _getAllParams(). You may also set request parameters using _setParam(); this is useful when forwarding to additional actions.

    To test whether or not a parameter exists (useful for logical branching), use _hasParam($key).

    [Note] Note

    _getParam() may take an optional second argument containing a default value to use if the parameter is not set or is empty. Using it eliminates the need to call _hasParam() prior to retrieving a value:

    <?php
    // Use 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;
    }
    ?>

7.7.5. View Integration

Zend_Controller_Action provides a rudimentary and flexible mechanism for view integration. Two methods accomplish this, initView() and render(); the former method lazy-loads the $view public property, and the latter renders a view based on the current requested action, using the directory hierarchy to determine the script path.

7.7.5.1. View Initialization

initView() initializes the view object. render() calls initView() in order to retrieve the view object, but it may be initialized at any time; by default it populates the $view property with a Zend_View object, but any class implementing Zend_View_Interface may be used. If $view is already initialized, it simply returns that property.

The default implementation makes the following assumption of the directory structure:

applicationOrModule/
    controllers/
        IndexController.php
    views/
        scripts/
            index/
                index.phtml
        helpers/
        filters/

In other words, view scripts are assumed to be in the views/scripts/ subdirectory, and the views subdirectory is assumed to contain sibling functionality (helpers, filters). When determining the view script name and path, the views/scripts/ directory will be used as the base path, with a directories named after the individual controllers providing a hierarchy of view scripts.

7.7.5.2. Rendering Views

render() has the following signature:

<?php
string render(string $action = null, string $name = null, bool $noController = false);
?>

render() renders a view script. If no arguments are passed, it assumes that the script requested is [controller]/[action].phtml (where .phtml is the value of the $viewSuffix property). Passing a value for $action will render that template in the [controller] subdirectory. To override using the [controller] subdirectory, pass a true value for $noController. Finally, templates are rendered into the response object; if you wish to render to a specific named segment in the response object, pass a value to $name.

Some examples:

<?php
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 foo/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
        $this->render('site', 'page', true);
    }
}

7.7.6. Utility Methods

Besides the accessors and view integration methods, Zend_Controller_Action has several utility methods for performing common tasks from within your action methods (or from pre-/post-dispatch).

  • _forward($action, $controller = null, $module = null, array $params = null): perform another action. If called in preDispatch(), the currently requested action will be skipped in favor of the new one. Otherwise, after the current action is processed, the action requested in _forward() will be executed.

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

    The options may include one or more of the following:

    • exit: whether or not to exit immediately. If requested, it will cleanly close any open sessions and perform the redirect.

      You may set this option globally within the controller using the setRedirectExit() accessor.

    • prependBase: whether or not to prepend the base URL registered with the request object to the URL provided.

      You may set this option globally within the controller using the setRedirectPrependBase() accessor.

    • code: what HTTP code to utilize in the redirect. By default, an HTTP 302 is utilized; any code between 301 and 306 may be used.

      You may set this option globally within the controller using the setRedirectCode() accessor.

7.7.7. Subclassing the Action Controller

By design, Zend_Controller_Action must be subclassed in order to create an action controller. At the minimum, you will need to define action methods that the controller may call.

Besides creating useful functionality for your web applications, you may also find that you're repeating much of the same setup or utility methods in your various controllers; if so, creating a common base controller class that extends Zend_Controller_Action could solve such redundancy.

7.7.7.1. How to Handle Non-Existent Actions

If a request to a controller is made that includes an undefined action method, Zend_Controller_Action::__call() will be invoked. __call() is, of course, PHP's magic method for method overloading.

By default, this method throws a Zend_Controller_Action_Exception indicating the requested action was not found in the controller. You should override this functionality if you wish to perform other operations.

For instance, if you wish to display an error message, you might write something like this:

<?php
class MyController extends Zend_Controller_Action
{
    public function __call($method, $args)
    {
        if ('Action' == substr($method, -6)) {
            // If the action method was not found, render the error template
            return $this->render('error');
        }

        // all other methods throw an exception
        throw new Exception('Invalid method "' . $method . '" called');
    }
}
?>

Another possibility is that you may want to forward on to a default controller page:

<?php
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 was not found, forward to the index action
            return $this->_forward('index');
        }

        // all other methods throw an exception
        throw new Exception('Invalid method "' . $method . '" called');
    }
}
?>

Besides overriding __call(), each of the initialization, utility, accessor, view, and dispatch hook methods mentioned previously in this chapter may be overridden in order to customize your controllers. As an example, if you are storing your view object in a registry, you may want to modify your initView() method with code resembling the following:

<?php
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;
    }
}
?>

Hopefully, from the information in this chapter, you can see the flexibility of this particular component and how you can shape it to your application's or site's needs.