Zend Framework: Part 4 – Modules

One aspect of the front controller is that you may define a modular directory structure for creating standalone components; these are called modules. Each module should be in its own directory and mirror the directory structure of the default module. so it should have a controllers subdirectory at the minimum, and typically a views subdirectory and other application subdirectories. To illustrate such a directory structure:

  docroot/
    index.php
  application/
    default/
      controllers/
        IndexController.php
        LoginController.php
        models/
        views/
        scripts/
          index/
          login/
        helpers/
        filters/
    blog/
      controllers/
        IndexController.php
      models/
      views/
        scripts/
          index/
      helpers/
      filters/

In this paradigm, the module name serves as a prefix to the controllers it contains. The above example contains one module controller, ‘Blog_IndexController’. Two global controllers, ‘IndexController’ and ‘LoginController’ are also defined; neither of these will be namespaced. With modular controllers, if a module has been specified but no controller, the dispatcher first looks for this default controller in the module path, and then falls back on the default controller found in the ‘default’, global, namespace.

The first step to making use of modules is to modify how you specify the controller directory list in the front controller. In the basic MVC series, you pass either an array or a string to setControllerDirectory(), or a path to addControllerDirectory(). When using modules, you need to alter your calls to these methods slightly.

With setControllerDirectory(), you will need to pass an associative array and specify key/value pairs of module name/directory paths. The special key default will be used for global controllers. All entries should contain a string key pointing to a single path, and the default key must be present. As an example:

$front->setControllerDirectory(array(
    'default' => '/path/to/application/controllers',
    'blog'    => '/path/to/application/blog/controllers'
));

The easiest way to specify module directories is to do so en masse, with all modules under a common directory and sharing the same structure. This can be done with addModuleDirectory().

/**
 * Assuming the following directory structure:
 * application/
 *   modules/
 *     default/
 *       controllers/
 *     blog/
 *       controllers/
 */
$front->addModuleDirectory('/path/to/application/modules');

The default route in Zend_Controller_Router_Rewrite is an object of type Zend_Controller_Router_Route_Module. This route expects one of the following routing schemas:

  • :module/:controller/:action/*
  • :controller/:action/*

Leave a Reply