Zend Framework & MVC Introduction

Create Your Project

In order to create your project, you must first download and extract Zend Framework.

Install Zend Framework

The easiest way to get Zend Framework along with a complete PHP stack is by installing » Zend Server. Zend Server has native installers for Mac OSX, Windows, Fedora Core, and Ubuntu, as well as a universal installation package compatible with most Linux distributions.

After you have installed Zend Server, the Framework files may be found under /usr/local/zend/share/ZendFramework on Mac OSX and Linux, and C:\Program Files\Zend\ZendServer\share\ZendFramework on Windows. The include_path will already be configured to include Zend Framework.

Alternately, you can » Download the latest version of Zend Framework and extract the contents; make a note of where you have done so.

Optionally, you can add the path to the library/ subdirectory of the archive to your php.ini's include_path setting.

That's it! Zend Framework is now installed and ready to use.

Create Your Project

Note: zf Command Line Tool
In your Zend Framework installation is a bin/ subdirectory, containing the scripts zf.sh and zf.bat for Unix-based and Windows-based users, respectively. Make a note of the absolute path to this script.
Wherever you see references to the command zf, please substitute the absolute path to the script. On Unix-like systems, you may want to use your shell's alias functionality: alias zf.sh=path/to/ZendFramework/bin/zf.sh.
If you have problems setting up the zf command-line tool, please refer to the manual.

Open a terminal (in Windows, Start -> Run, and then use cmd). Navigate to a directory where you would like to start a project. Then, use the path to the appropriate script, and execute one of the following:

  1. % zf create project quickstart

Running this command will create your basic site structure, including your initial controllers and views. The tree looks like the following:

  1. quickstart
  2. |-- application
  3. |   |-- Bootstrap.php
  4. |   |-- configs
  5. |   |   `-- application.ini
  6. |   |-- controllers
  7. |   |   |-- ErrorController.php
  8. |   |   `-- IndexController.php
  9. |   |-- models
  10. |   `-- views
  11. |       |-- helpers
  12. |       `-- scripts
  13. |           |-- error
  14. |           |   `-- error.phtml
  15. |           `-- index
  16. |               `-- index.phtml
  17. |-- library
  18. |-- public
  19. |   |-- .htaccess
  20. |   `-- index.php
  21. `-- tests
  22.     |-- application
  23.     |   `-- bootstrap.php
  24.     |-- library
  25.     |   `-- bootstrap.php
  26.     `-- phpunit.xml

At this point, if you haven't added Zend Framework to your include_path, we recommend either copying or symlinking it into your library/ directory. In either case, you'll want to either recursively copy or symlink the library/Zend/ directory of your Zend Framework installation into the library/ directory of your project. On unix-like systems, that would look like one of the following:

  1. # Symlink:
  2. % cd library; ln -s path/to/ZendFramework/library/Zend .
  3.  
  4. # Copy:
  5. % cd library; cp -r path/to/ZendFramework/library/Zend .

On Windows systems, it may be easiest to do this from the Explorer.

Now that the project is created, the main artifacts to begin understanding are the bootstrap, configuration, action controllers, and views.

The Bootstrap

Your Bootstrap class defines what resources and components to initialize. By default, Zend Framework's Front Controller is initialized, and it uses the application/controllers/ as the default directory in which to look for action controllers (more on that later). The class looks like the following:

  1. // application/Bootstrap.php
  2.  
  3. class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
  4. {
  5. }

As you can see, not much is necessary to begin with.

Configuration

While Zend Framework is itself configurationless, you often need to configure your application. The default configuration is placed in application/configs/application.ini, and contains some basic directives for setting your PHP environment (for instance, turning error reporting on and off), indicating the path to your bootstrap class (as well as its class name), and the path to your action controllers. It looks as follows:

  1. ; application/configs/application.ini
  2.  
  3. [production]
  4. phpSettings.display_startup_errors = 0
  5. phpSettings.display_errors = 0
  6. includePaths.library = APPLICATION_PATH "/../library"
  7. bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
  8. bootstrap.class = "Bootstrap"
  9. appnamespace = "Application"
  10. resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
  11. resources.frontController.params.displayExceptions = 0
  12.  
  13. [staging : production]
  14.  
  15. [testing : production]
  16. phpSettings.display_startup_errors = 1
  17. phpSettings.display_errors = 1
  18.  
  19. [development : production]
  20. phpSettings.display_startup_errors = 1
  21. phpSettings.display_errors = 1

Several things about this file should be noted. First, when using INI-style configuration, you can reference constants directly and expand them; APPLICATION_PATH is actually a constant. Additionally note that there are several sections defined: production, staging, testing, and development. The latter three inherit settings from the "production" environment. This is a useful way to organize configuration to ensure that appropriate settings are available in each stage of application development.

Action Controllers

Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.

An action controller should have one or more methods ending in "Action"; these methods may then be requested via the web. By default, Zend Framework URLs follow the schema /controller/action, where "controller" maps to the action controller name (minus the "Controller" suffix) and "action" maps to an action method (minus the "Action" suffix).

Typically, you always need an IndexController, which is a fallback controller and which also serves the home page of the site, and an ErrorController, which is used to indicate things such as HTTP 404 errors (controller or action not found) and HTTP 500 errors (application errors).

The default IndexController is as follows:

  1. // application/controllers/IndexController.php
  2.  
  3. class IndexController extends Zend_Controller_Action
  4. {
  5.  
  6.     public function init()
  7.     {
  8.         /* Initialize action controller here */
  9.     }
  10.  
  11.     public function indexAction()
  12.     {
  13.         // action body
  14.     }
  15. }

And the default ErrorController is as follows:

  1. // application/controllers/ErrorController.php
  2.  
  3. class ErrorController extends Zend_Controller_Action
  4. {
  5.  
  6.     public function errorAction()
  7.     {
  8.         $errors = $this->_getParam('error_handler');
  9.  
  10.         switch ($errors->type) {
  11.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
  12.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
  13.             case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
  14.  
  15.                 // 404 error -- controller or action not found
  16.                 $this->getResponse()->setHttpResponseCode(404);
  17.                 $this->view->message = 'Page not found';
  18.                 break;
  19.             default:
  20.                 // application error
  21.                 $this->getResponse()->setHttpResponseCode(500);
  22.                 $this->view->message = 'Application error';
  23.                 break;
  24.         }
  25.  
  26.         $this->view->exception = $errors->exception;
  27.         $this->view->request   = $errors->request;
  28.     }
  29. }

You'll note that (1) the IndexController contains no real code, and (2) the ErrorController makes reference to a "view" property. That leads nicely into our next subject.

Views

Views in Zend Framework are written in plain old PHP. View scripts are placed in application/views/scripts/, where they are further categorized using the controller names. In our case, we have an IndexController and an ErrorController, and thus we have corresponding index/ and error/ subdirectories within our view scripts directory. Within these subdirectories, you will then find and create view scripts that correspond to each controller action exposed; in the default case, we thus have the view scripts index/index.phtml and error/error.phtml.

View scripts may contain any markup you want, and use the <?php opening tag and ?> closing tag to insert PHP directives.

The following is what we install by default for the index/index.phtml view script:

  1. <!-- application/views/scripts/index/index.phtml -->
  2. <style>
  3.  
  4.     a:link,
  5.     a:visited
  6.     {
  7.         color: #0398CA;
  8.     }
  9.  
  10.     span#zf-name
  11.     {
  12.         color: #91BE3F;
  13.     }
  14.  
  15.     div#welcome
  16.     {
  17.         color: #FFFFFF;
  18.         background-image: url(http://framework.zend.com/images/bkg_header.jpg);
  19.         width:  600px;
  20.         height: 400px;
  21.         border: 2px solid #444444;
  22.         overflow: hidden;
  23.         text-align: center;
  24.     }
  25.  
  26.     div#more-information
  27.     {
  28.         background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif);
  29.         height: 100%;
  30.     }
  31.  
  32. </style>
  33. <div id="welcome">
  34.     <h1>Welcome to the <span id="zf-name">Zend Framework!</span><h1 />
  35.     <h3>This is your project's main page<h3 />
  36.     <div id="more-information">
  37.         <p>
  38.             <img src="http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png" />
  39.         </p>
  40.  
  41.         <p>
  42.             Helpful Links: <br />
  43.             <a href="http://framework.zend.com/">Zend Framework Website</a> |
  44.             <a href="http://framework.zend.com/manual/en/">Zend Framework
  45.                 Manual</a>
  46.         </p>
  47.     </div>
  48. </div>

The error/error.phtml view script is slightly more interesting as it uses some PHP conditionals:

  1. <!-- application/views/scripts/error/error.phtml -->
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN";
  3.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
  4. <html xmlns="http://www.w3.org/1999/xhtml">
  5. <head>
  6.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7.   <title>Zend Framework Default Application</title>
  8. </head>
  9. <body>
  10.   <h1>An error occurred</h1>
  11.   <h2><?php echo $this->message ?></h2>
  12.  
  13.   <?php if ('development' == $this->env): ?>
  14.  
  15.   <h3>Exception information:</h3>
  16.   <p>
  17.       <b>Message:</b> <?php echo $this->exception->getMessage() ?>
  18.   </p>
  19.  
  20.   <h3>Stack trace:</h3>
  21.   <pre><?php echo $this->exception->getTraceAsString() ?>
  22.   </pre>
  23.  
  24.   <h3>Request Parameters:</h3>
  25.   <pre><?php echo var_export($this->request->getParams(), 1) ?>
  26.   </pre>
  27.   <?php endif ?>
  28.  
  29. </body>
  30. </html>

Create a virtual host

For purposes of this quick start, we will assume you are using the » Apache web server. Zend Framework works perfectly well with other web servers -- including Microsoft Internet Information Server, lighttpd, nginx, and more -- but most developers should be famililar with Apache at the minimum, and it provides an easy introduction to Zend Framework's directory structure and rewrite capabilities.

To create your vhost, you need to know the location of your httpd.conf file, and potentially where other configuration files are located. Some common locations:

  • /etc/httpd/httpd.conf (Fedora, RHEL, and others)

  • /etc/apache2/httpd.conf (Debian, Ubuntu, and others)

  • /usr/local/zend/etc/httpd.conf (Zend Server on *nix machines)

  • C:\Program Files\Zend\Apache2\conf (Zend Server on Windows machines)

Within your httpd.conf (or httpd-vhosts.conf on some systems), you will need to do two things. First, ensure that the NameVirtualHost is defined; typically, you will set it to a value of "*:80". Second, define a virtual host:

  1. <VirtualHost *:80>
  2.     ServerName quickstart.local
  3.     DocumentRoot /path/to/quickstart/public
  4.  
  5.     SetEnv APPLICATION_ENV "development"
  6.  
  7.     <Directory /path/to/quickstart/public>
  8.         DirectoryIndex index.php
  9.         AllowOverride All
  10.         Order allow,deny
  11.         Allow from all
  12.     </Directory>
  13. </VirtualHost>

There are several things to note. First, note that the DocumentRoot setting specifies the public subdirectory of our project; this means that only files under that directory can ever be served directly by the server. Second, note the AllowOverride, Order, and Allow directives; these are to allow us to use htacess files within our project. During development, this is a good practice, as it prevents the need to constantly restart the web server as you make changes to your site directives; however, in production, you should likely push the content of your htaccess file into your server configuration and disable this. Third, note the SetEnv directive. What we are doing here is setting an environment variable for your virtual host; this variable will be picked up in the index.php and used to set the APPLICATION_ENV constant for our Zend Framework application. In production, you can omit this directive (in which case it will default to the value "production") or set it explicitly to "production".

Finally, you will need to add an entry in your hosts file corresponding to the value you place in your ServerName directive. On *nix-like systems, this is usually /etc/hosts; on Windows, you'll typically find it in C:\WINDOWS\system32\drivers\etc. Regardless of the system, the entry will look like the following:

  1. 127.0.0.1 quickstart.local

Start your webserver (or restart it), and you should be ready to go.

Checkpoint

At this point, you should be able to fire up your initial Zend Framework application. Point your browser to the server name you configured in the previous section; you should be able to see a welcome page at this point.


Zend Framework & MVC Introduction