Tag Archives: zend framework

When Your Zend Framework Project returns Page Not Found Errors but Everything is Configured Correctly CodeUnit 29 APR 2011

It can be pretty frustrating. Your Zend Framework project is configured 100% correctly. Mod Rewrite is enabled and working on your server, the .htaccess file is configured correctly and working, all your controllers are correctly created and specified, all with the necessary index actions, your modules are healthy, in short everything is looking 100% like all the examples taught you. Yet for some reason when you try and browse your site, you keep getting Page Not Found, Controller not specified error messages!

I had this issue recently and it was causing me to tear my hair out in frustration. My project was modularized and I was using a menu in the layout, defined in the application.ini file. Everything looked correct and on my Windows dev box all navigation seemed to be working correctly. However, copy the code over to the Ubuntu server and the navigation suddenly broke. Much frustration later, I eventually twigged as to what was wrong. The URLs contained in my menu.

As we all know, camelCase is the default way to express controller and action names in Zend. However, what we do sometimes forget, is that the default URLs are expressed in lowercase, with hyphens indicating the start of a uppercase letter.

In other words while http://myproject/ViewLogs/ may look right to you at first glance, because it matches the name of the controller perfectly, the correct URL is actually http://myproject/view-logs/.

If you remember that, then you shouldn’t go wrong. (Wish I had, to be honest).

So the simple fix was to change the way I specified my menu, from:

resources.navigation.pages.oslo.pages.sub.label = "Allowed Access"
resources.navigation.pages.oslo.pages.sub.module = "oslo"
resources.navigation.pages.oslo.pages.sub.controller = "AllowedAccess"
resources.navigation.pages.oslo.pages.sub.action = "index"


resources.navigation.pages.oslo.pages.sub.label = "Allowed Access"
resources.navigation.pages.oslo.pages.sub.module = "oslo"
resources.navigation.pages.oslo.pages.sub.controller = "allowed-access"
resources.navigation.pages.oslo.pages.sub.action = "index"

And now you know.

Zend Framework: How to Build a Dynamic Layout by Setting Variables in your Controllers CodeUnit 04 APR 2011

I have a Zend Framework website that is broken up into modules. Accordingly, I want my single layout.phtml Layout script to dynamically change ever so slightly depending on what module or rather controller I hit – in my case change the header image. So how do we do this?

Well the first thing is gaining access to the Layout object so that you can set some variables in this.

To gain access within action controllers, use the layout() action helper:

// Calling helper as a method of the helper broker:
$helper = $this->_helper->getHelper('Layout');
$layout = $helper->getLayoutInstance();

To gain access within view scripts, use the layout() view helper:

$layout = $this->layout();

To gain access via the bootstrap, retrieve the layout resource:

$layout = $bootstrap->getResource('Layout');

Finally if you still can’t get a layout object to work with, use the static method (not entirely recommended):

$layout = Zend_Layout::getMvcInstance();

Now that you have a $layout object to work with, you’ll probably want to assign some sort of variable value to it in order to dynamically affect your layout.phtml file. To set a variable you can either directly assign with the = operator or make use of the assign() method:

// Setting content:
$layout->somekey = "foo"
// Using the assign() method:
$layout->assign('someotherkey', 'bar');

Okay, now that we have a variable stored in the layout object, it becomes trivial to make our layout dynamic. For example, having previously added a value to $layout->mainheaderlogo = ‘image1.png’, we can now add the following to our layout.phtml file:

<div id=”logobanner”><a href=”/”><img src=”/images/<?php echo $this->layout()->mainheaderlogo; ?>” /></a></div>

And now you know. Nifty.

(Update: Or you should probably really learn to use Zend View Placeholders correctly, as they are the correct way of making your layout more Dynamic!!)

How to Create a Zend Framework Project that Uses Modules CodeUnit 01 APR 2011

If your website can be logically split into a number of different functionalities, it makes sense to group those functionalities accordingly. In Zend terminology we are talking about modules, literally the folder splitting of logically grouped pieces of functionality. However, by default a generated Zend Framework project isn’t modular and to get the thing properly modularized, here’s what you have to do.

Using Zend Framework 1.11.4:

First, create your project like you normally would via the command line interface:

zf create project moduleproject
cd moduleproject

Next, create your default module. This will house module that will handle all requests to the root of your site, in other words http://moduleproject/helloworld or http://moduleproject/

zf create module default

Now add the all important index and error controllers:

zf create controller Index index-action-included[=1] default
zf create controller Error -m default

Replace the contents of the generated error controller with the following contents: (c:moduleprojectapplicationmodulesdefaultcontrollersErrorController.php)

class Default_ErrorController extends Zend_Controller_Action

    public function errorAction()
        $errors = $this->_getParam('error_handler');
        if (!$errors || !$errors instanceof ArrayObject) {
            $this->view->message = 'You have reached the error page';
        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $priority = Zend_Log::NOTICE;
                $this->view->message = 'Page not found';
                // application error
                $priority = Zend_Log::CRIT;
                $this->view->message = 'Application error';
        // Log exception, if logger available
        if ($log = $this->getLog()) {
            $log->log($this->view->message, $priority, $errors->exception);
            $log->log('Request Parameters', $priority, $errors->request->getParams());
        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        $this->view->request   = $errors->request;

    public function getLog()
        $bootstrap = $this->getInvokeArg('bootstrap');
        if (!$bootstrap->hasResource('Log')) {
            return false;
        $log = $bootstrap->getResource('Log');
        return $log;


Next create an error view that will be used by Error controller: (c:moduleprojectapplicationmodulesdefaultviewsscriptserrorerror.phtml)

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Zend Framework Default Application</title>
<h1>An error occurred</h1>
<h2><?php echo $this->message ?></h2>

<?php if (isset($this->exception)): ?>

<h3>Exception information:</h3>
<b>Message:</b> <?php echo $this->exception->getMessage() ?>

<h3>Stack trace:</h3>
<pre><?php echo $this->exception->getTraceAsString() ?>

<h3>Request Parameters:</h3>
<pre><?php echo $this->escape(var_export($this->request->getParams(), true)) ?>

<?php endif ?>


Finally, add the following line in the production section of your application.ini file: (c:moduleprojectapplicationconfigsapplication.ini)

resources.modules[] =

Set your environment so that errors are display and then first hit your project URL to make sure it is showing up correctly, i.e. http://moduleproject/. Next, hit a non-existent URL like http://moduleproject/fail and look at the resulting error page. If the request parameters reads array( … ‘module’ => default’ … ) then you’re finished.

You now have a completely modularized project, which you can add to by running

zf create module module2
zf create controller index -m module2


How to create Menus and Breadcrumbs in Zend Framework using the Config .ini File CodeUnit 30 MAR 2011

To create navigation menu items in the Zend Framework by storing all the information in your config application.ini file turns out to be a relatively simple affair.

First add the following line to your application.ini file:

resources.navigation.storage.registry[] = 

Next define your pages as follows:

resources.navigation.pages.home.label = "Home"
resources.navigation.pages.home.controller = "index"
resources.navigation.pages.home.action = "index"

resources.navigation.pages.item2.label = "Next Item"
resources.navigation.pages.item2.controller = "nextitem"
resources.navigation.pages.item2.action = "index"

;for modules try:
resources.navigation.pages.home.label = "Home"
resources.navigation.pages.home.module = "admin"
resources.navigation.pages.home.controller = "index"
resources.navigation.pages.home.action = "index"

;for sub menu items:
resources.navigation.pages.home.pages.sub.label = "Sub1"
resources.navigation.pages.home.pages.sub.controller = "sub"
resources.navigation.pages.home.pages.sub.action = "index"

Now that your pages have been defined, your bootstrap file can be used to initiate the layout, which in turn initiates the navigation object automatically. If you check your bootstrap file, you should have a function looking something like this:

protected function _initNavigationConfig()
    $layout = $this->getResource('layout');
    $view = $layout->getView();

Finally, to actually print out the navigation menu in your layout, simply add the following line somewhere in your layout.phtml file:


As easy as that.

Note that if you want breadcrumbs in your layout, you can use this:

echo $this->navigation()->breadcrumbs()


Worth Reading: Zend Framework in Action (Rob Allen, Nick Lo, Steven Brown) CodeUnit 18 MAR 2011

Let me start off if you want to learn to program, or learn to program in PHP specifically, you don’t learn by starting off using a framework. That is not going to teach you anything other than making you unable to solve small problems in the most efficient manner.

However, if you are already a programmer and have been asked to pick up Zend, the first thing you’ll find is that the learning curve into Zend is steep. Very, very steep.

So much so that there is no way a bunch of simple tutorials are going to get you properly versed in the framework, leaving us in other words with proper learning materials – i.e. books.

And if you are looking for a good book, look no further than the excellent Zend Framework in Action by Rob Allen, Nick Lo and Steven Brown, published by Manning.

In depth, covering all aspects of the Zend Framework in an easy to understand manner, padding out with a lot of examples (and more importantly, a nice complex real world website that gets carried throughout the text), Zend Framework in Action is an excellent read to get you properly up and running and well on your way to becoming proficient in the world of Zend.


How to Create a Zend Project from the Command Line with zf Tips, Tricks and Tutorials 16 MAR 2011

To generate an empty project shell using the Zend Framework is pretty easy thanks to the powerful zf command line utility.

To create a project, simply open a command line window, browse to the directory in which you want to create your Zend Framework project and enter:

zf create project "My Project"

zend-zf-logowhere My Project is the name of the project you want to generate. Note that for project names containing spaces, you can make use of double quotes to enclose. Also, zf (or rather the Zend bin directory) should be added to your system PATH in order to give it global visibility and thus make it easier to use.

The program will create a directory matching the name of your given project, and populate it with all the necessary Zend shell structures. You should at a minimum have application, docs, library, public and tests folders in the root, as well as a .zfproject.xml file. In the public folder, check that there is a .htaccess file containing the following rules:

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

Finally, you need to either symlink the library folder to that of the installed Zend framework’s library folder on the system, or just copy the Zend framework library folder’s contents into the library folder of your new project directory.


Simple Zend Tutorial for People Starting Out… with Zend CodeUnit 14 MAR 2011

This post serves more as a bookmark for me than anything else, now that I have been tasked with learning the icky world of Zend and its MVC pattern from the powers above here at work. Learning Zend is not for the faint hearted, that is for sure, and just finding your feet takes a fair bit of reading.

One of the best introductory and explanatory tutorials introducing new users to Zend that I have come across yet, is written by one Nicholas Chase, a consultant at Backstop Media who writes for the IBM developerWorks website.

Originally written way back in 2006 and consequently updated in January 2011, this excellent nine part tutorial covers just about everything someone starting out needs to know, including database work, feed and inputFilter usage, HTTPClient and PDF, e-mail sending and searching, connecting to outside services like Flickr and even adding AJAX to your application.

The tutorial segments are all well written, well laid out, with detailed explanations seemingly always forthcoming.

And hey, after going through everything you’ll even have your very own RSS reader to show off! ;)

You can kick off the tutorial by clicking here.


Related Link: http://www.ibm.com/developerworks/opensource/library/os-php-zend1/

How to Install the Zend Framework in Windows Vista for a Web Developer CodeUnit 11 MAR 2011

If you already have a web development environment set up on your machine and don’t necessarily want to run the whole Zend Server package and instead just want to create Zend projects using the Zend Framework, then this simple how to install Zend Framework tutorial should be perfect for you.

Step 1) Grab Zend Framework

Download the latest version of the framework from http://framework.zend.com/download/latest and unzip it to where you want it installed/located on your machine.

Step 2) Set up System PATH Variable

Add the newly extracted Zend Framework package to your system PATH variable: In VISTA right click on the Computer (My Computer) icon and click on the Advanced System Settings link under the tasks menu on the left. At the bottom of the resulting System Properties dialog will be a button that reads Environment Variables. Click this.

Browse through the list of Variables under the System variables section of the Environment Variables dialog. If you already have a PATH variable, click Edit. If you don’t click on New. Variable name should be set to PATH. The value should be set to the folder in which you extracted the framework: e.g. C:ZendFramework-1.11.4bin

Note that while you are here, you may as well check if your PHP bin directory (basically the directory containing php.exe) is listed under the PATH variable. If not, add it. Mulitple locations can be defined under the PATH variable, using semi-colon ‘;’ to delimit them: e.g. C:ZendFramework-1.11.4bin;C:xamppphp

To test that this has been done correctly, open a command prompt (Windows button->Run…->cmd) and type in zf. If it complains about zf not being an executable, then your path setting is wrong. If it works, you’ll get some help information from the zf command.

Step 3) Generate Zend project

Now to generate your Zend project. Still in the command prompt, browse to where you want to create your project: e.g. cd c:vhostszend-projects. Now, enter:

zf create project MyProjectName

where MyProjectName is the name of your Zend project. This should generate a folder structure under c:vhostszend-projectsMyProjectName that will contain all the necessary Zend folder/file structures necessary for your work. For example, you should see folders under the root like application, library and public.

Note that sometimes this process doesn’t properly generate the necessary library contents. To get around this, go to the folder in which you originally extracted the Zend Framework to, locate the library folder in its root and copy its contents to the library folder under your project’s root.

Step 4) Set up Virtual Host

Locate your Apache2 httpd-vhosts.conf file. If it isn’t using a separate file to maintain its list of virtual hosts, then locate its httpd.conf file. In it, you need to add the virtual host information for your new project. Locate the section dealing with virtual hosts and add the following:

<VirtualHost *:80>
DocumentRoot c:/vhosts/zend-projects/MyProjectName/public
ServerName  MyProjectName
<Directory "c:/vhosts/zend-projects/MyProjectName/public/">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all

Save your .conf file and restart Apache2.

Step 5) Edit Your hosts File

Finally, we just need to edit our Windows host file so that we can work on our project. Locate and open in notepad (PSPad is my favourite) C:windowssystem32driversetchosts. Add the following line and save: MyProjectName

Step 6) Test Installation

And we’re done. If you now hit http://MyProjectName/ from a browser you should be presented with a Zend Welcome splash page. (If you are presented with a failed to open stream error, remember the library contents note I made in step 3.)

Nifty – or should that rather be, Good Luck!? :)