Zend_Controller Quick Start - Zend_Controller

Zend_Controller Quick Start


Zend_Controller is the heart of Zend Framework's MVC system. MVC stands for » Model-View-Controller and is a design pattern targeted at separating application logic from display logic. Zend_Controller_Front implements a » Front Controller pattern, in which all requests are intercepted by the front controller and dispatched to individual Action Controllers based on the URL requested.

The Zend_Controller system was built with extensibility in mind, either by subclassing the existing classes, writing new classes that implement the various interfaces and abstract classes that form the foundation of the controller family of classes, or writing plugins or action helpers to augment or manipulate the functionality of the system.

Quick Start

If you need more in-depth information, see the following sections. If you just want to get up and running quickly, read on.

Create the Filesystem Layout

The first step is to create your file system layout. The typical layout is as follows:

  1. application/
  2.     controllers/
  3.         IndexController.php
  4.     models/
  6.         scripts/
  7.             index/
  8.                 index.phtml
  9.         helpers/
  10.         filters/
  11. html/
  12.     .htaccess
  13.     index.php

Set the Document Root

In your web server, point your document root to the html/ directory of the above file system layout.

Create the Rewrite Rules

Edit the html/.htaccess file above to read as follows:

  1. RewriteEngine On
  2. RewriteCond %{REQUEST_FILENAME} -s [OR]
  3. RewriteCond %{REQUEST_FILENAME} -l [OR]
  4. RewriteCond %{REQUEST_FILENAME} -d
  5. RewriteRule ^.*$ - [NC,L]
  6. RewriteRule ^.*$ index.php [NC,L]

Note: Learn about mod_rewrite
The above rewrite rules allow access to any file under your virtual host's document root. If there are files you do not want exposed in this way, you may want to be more restrictive in your rules. Go to the Apache website to » learn more about mod_rewrite.

If using IIS 7.0, use the following as your rewrite configuration:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3.      <system.webServer>
  4.          <rewrite>
  5.              <rules>
  6.                  <rule name="Imported Rule 1" stopProcessing="true">
  7.                      <match url="^.*$" />
  8.                      <conditions logicalGrouping="MatchAny">
  9.                          <add input="{REQUEST_FILENAME}"
  10.                              matchType="IsFile" pattern=""
  11.                              ignoreCase="false" />
  12.                          <add input="{REQUEST_FILENAME}"
  13.                              matchType="IsDirectory"
  14.                              pattern="" ignoreCase="false" />
  15.                      </conditions>
  16.                      <action type="None" />
  17.                  </rule>
  18.                  <rule name="Imported Rule 2" stopProcessing="true">
  19.                      <match url="^.*$" />
  20.                      <action type="Rewrite" url="index.php" />
  21.                  </rule>
  22.              </rules>
  23.          </rewrite>
  24.      </system.webServer>
  25. </configuration>

The above rules will route requests to existing resources (existing symlinks, non-empty files, or non-empty directories) accordingly, and all other requests to the front controller.

Note: The above rewrite rules are for Apache; for examples of rewrite rules for other web servers, see the router documentation.

Create the Bootstrap File

The bootstrap file is the page all requests are routed through -- html/index.php in this case. Open up html/index.php in the editor of your choice and add the following:

  1. Zend_Controller_Front::run('/path/to/app/controllers');

This will instantiate and dispatch the front controller, which will route requests to action controllers.

Create the Default Action Controller

Before discussing action controllers, you should first understand how requests are routed in Zend Framework. By default, the first segment of a URL path maps to a controller, and the second to an action. For example, given the URL, the path is /roadmap/components, which will map to the controller roadmap and the action components. If no action is provided, the action index is assumed, and if no controller is provided, the controller index is assumed (following the Apache convention that maps a DirectoryIndex automatically).

Zend_Controller's dispatcher then takes the controller value and maps it to a class. By default, it Title-cases the controller name and appends the word Controller. Thus, in our example above, the controller roadmap is mapped to the class RoadmapController.

Similarly, the action value is mapped to a method of the controller class. By default, the value is lower-cased, and the word Action is appended. Thus, in our example above, the action components becomes componentsAction(), and the final method called is RoadmapController::componentsAction().

So, moving on, let's now create a default action controller and action method. As noted earlier, the default controller and action called are both index. Open the file application/controllers/IndexController.php, and enter the following:

  1. /** Zend_Controller_Action */
  2. class IndexController extends Zend_Controller_Action
  3. {
  4.     public function indexAction()
  5.     {
  6.     }
  7. }

By default, the ViewRenderer action helper is enabled. What this means is that by simply defining an action method and a corresponding view script, you will immediately get content rendered. By default, Zend_View is used as the View layer in the MVC. The ViewRenderer does some magic, and uses the controller name (e.g., index) and the current action name (e.g., index) to determine what template to pull. By default, templates end in the .phtml extension, so this means that, in the above example, the template index/index.phtml will be rendered. Additionally, the ViewRenderer automatically assumes that the directory views/ at the same level as the controller directory will be the base view directory, and that the actual view scripts will be in the views/scripts/ subdirectory. Thus, the template rendered will be found in application/views/scripts/index/index.phtml.

Create the View Script

As mentioned in the previous section, view scripts are found in application/views/scripts/; the view script for the default controller and action is in application/views/scripts/index/index.phtml. Create this file, and type in some HTML:

  1. <!DOCTYPE html
  2. PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  3. "">
  4. <html>
  5. <head>
  6.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7.   <title>My first Zend Framework App</title>
  8. </head>
  9. <body>
  10.     <h1>Hello, World!</h1>
  11. </body>
  12. </html>

Create the Error Controller

By default, the error handler plugin is registered. This plugin expects that a controller exists to handle errors. By default, it assumes an ErrorController in the default module with an errorAction() method:

  1. class ErrorController extends Zend_Controller_Action
  2. {
  3.     public function errorAction()
  4.     {
  5.     }
  6. }

Assuming the already discussed directory layout, this file will go in application/controllers/ErrorController.php. You will also need to create a view script in application/views/scripts/error/error.phtml; sample content might look like:

  1. <!DOCTYPE html
  2. PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  3. "">
  4. <html>
  5. <head>
  6.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7.   <title>Error</title>
  8. </head>
  9. <body>
  10.     <h1>An error occurred</h1>
  11.     <p>An error occurred; please try again later.</p>
  12. </body>
  13. </html>

View the Site!

With your first controller and view under your belt, you can now fire up your browser and browse to the site. Assuming is your domain, any of the following URLs will get to the page we've just created:




You're now ready to start creating more controllers and action methods. Congratulations!


© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.