• Subscribe to the RSS feed!
  • Subscribe by Email
  • home
  • blog
  • dev
  • Recent Posts

    • Toggler
      • on February 4, 2010
    • Book review - jQuery 1.3 with PHP
      • on January 6, 2010
    • 2009 in a few words
      • on January 2, 2010
    • Bad Firebug!
      • on December 21, 2009
    • Posterous
      • on December 2, 2009
    • Chaining routes in Zend Framework
      • on November 27, 2009
    • Zend Framework bug hunt days
      • on November 22, 2009
    • Zend Framework 1.8 Web Application Development book review
      • on November 17, 2009
    • A book review
      • on October 11, 2009
    • Playing with Zend_Navigation and routes
      • on August 9, 2009
  • Recent Comments

    • Aryashree Pritikrishna
      • on January 28th @ 9:10 am
    • Michl
      • on January 15th @ 10:09 am
    • Robert
      • on January 2nd @ 1:36 pm
    • Ivan
      • on January 2nd @ 1:33 pm
    • Keith Pope
      • on January 1st @ 11:57 am
    • Jani Hartikainen
      • on December 29th @ 8:55 am
    • johnjbarton
      • on December 22nd @ 1:01 am
    • Robert
      • on December 21st @ 11:55 pm
    • René Silva
      • on December 21st @ 11:47 pm
    • Robert van Drunen
      • on December 21st @ 6:37 pm
  • Tags

    • php
    • framework
    • zend
    • example
    • random
    • about
    • site
    • ubuntu
    • blog
    • introduction
    • book
    • wordpress
    • linux
    • apache
    • lamp
    • setup
    • review
    • open source
    • svn
    • comic
  • Categories

    • Blablabla
    • Development
    • Free time
    • Places on the web
    • Programming
    • Software
  • Archives

    • February 2010
    • January 2010
    • December 2009
    • November 2009
    • October 2009
    • August 2009
    • May 2009
    • March 2009
    • February 2009
    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • September 2008
  • Find me on

    • DZone
    • Google Code
    • Google Reader
    • Last.fm
    • StumbleUpon
    • Twitter
    • Vimeo
  • Friends and Blogs

    • Andrew Taylor
    • Andy Sowards
    • Bojan Pejić
    • Eran Galperin
    • Graham Smith
    • Jani Hartikainen
    • Jasper Tandy
    • Matthew Turland
    • Matthew Weier O’Phinney
    • Miff
    • Miloš Ćuković
    • Nebojša Radović
    • Nemanja Avramović
    • Nemanja Tobić
    • Nikola Krajačić
    • Nikola Plejić
    • Pádraic Brady
    • Rob Allen
    • Swizec Teller
    • Vladimir Stanković
    • WeAreJustCreative
    • Željko Stevanović
  • I use

    • 960 Grid System
    • jQuery
    • Notepad++
    • Subversion
    • Trac
    • Vim
    • Zend Framework

Starting with Zend Framework

by Robert Basic on October 7th, 2008

Zend Framework is a big & heavy object-oriented framework for PHP. I started working with ZF a couple of months ago, I liked it’s documention (it’s very well documented) and decided to stick with this framework. Here is the latest version of the framework — at the time of writing v1.6.1.

It supports the MVC pattern, which helps separating business logic from viewing logic. It supports a great number of API’s, such as Delicious API, Flickr API, Yahoo API, Akismet API and many more.

The advantages of using a framework is that it is enforcing the developer to write code using a coding standard, it is well documented and well supported, and it is a lot easier to work in a 2+ person team using a framework. If you are a one—man team, someday you may want to add more developers to your projects; the process of their settling in will be very comfortable if you are using a framework.

Choose yourself a framework that best suits your needs, or write your own (be sure to make good documentation, also!). To be honest, I wasn’t looking at other frameworks, just ZF, but I knew right away that it is good for me. Prior to this post I did a little research on other frameworks, and I’m still sure that I made the right choice by choosing ZF.

You can read a bit more about ZF in general on the overview page.

How does it work?

Before anything, we should take a look how does the ZF work, when used in the MVC manner. ZF has a thingy, called Front Controller. When a user is accessing a web page, the Front Controller is called: it’s determining what should be done with the input and which further objects should be instantiated and methods called, and in what order.

E.g., if one makes a page request like: http://example.com/news/last/, first, the Front Controller is called. The Front Controller sets up the environment, loads up some files and classes, etc., then it calls a controller called “News” and an action called “Last” which is to be found inside the “News” controller. If it fails to find the “News” controller or the “Last” action, than it can show the user some error page, or to print out the error itself, depending how it is set up. If everything is OK, then it shows the user the content…

This explanation is very basic, as I intend to dedicate one big post to the Front Controller itself, going deep into details…

Some terms explained

Bootstrap file: all page requests are routed through this file, the Front Controller object is created here.

A module is a part of an application which has it’s own controllers, actions, view scripts, models, configuration files. For example, a page can have a default module and a blog module, where each module has its own Index Controller, Administrator Controller, and have its own unique controllers, like a Comments Controller for the blog module.

A controller is a class which has its own actions and can have its own functions. It controls the data received from the user or from the database, and decides what to do with it. The controller is responsible for one set of things, e.g. a News Controller would list latest news, list news from a particular source, show the archive, etc.

An action is a function inside a controller, which is responsible for doing some action, e.g. action for showing news.

A model receives data from the Controller, and sends data to the Controller. Database related stuff — selecting, inserting, updating, deleting — should be only in the model. Filtering data that is to be inserted into the database should be done in the Controller, not in the model.

A view script is responsible to show the data received from the Controller to the user.

A view helper script is to help to do some automating in the view scripts, like formatting dates, generating form elements, etc.

Just for the record, in further examples, “Dummy” will be referring to a module, “Foo” will be referring to a controller inside the “Dummy” module and “Bar” will be referring to an action inside the “Foo” controller.

Basic file structure

Here’s an example of a file structure for a ZF based application — after the # sign are comments:

/
|--library/
|  |--Zend/ # Zend core
|--application/ # Core of our application
|   |--default/ # The Default module
|       |--config/ # Some configuration files
|          |--config.ini
|       |--controllers/ # Controllers go here
|          |--IndexController.php
|          |--FooController.php
|       |--models/ # Models...
|          |--ModelName.php
|       |--views/ # View related stuff...
|          |--helpers/
|          |--scripts/
|             |--index/ # View files for the Index Controller
|               |--index.phtml # For the default index action
|             |--foo/ # View files for the Foo Controller
|               |--index.phtml # For the default index action
|               |--bar.phtml # For a bar action in the Foo Controller
|             |--layout.phtml # For layout
|   |--dummy/ # A Dummy module...
|       |--config/
|          |--config.ini
|       |--controllers/
|          |--IndexController.php
|          |--FooController.php
|       |--models/
|       |--views/
|          |--helpers/
|          |--scripts/
|             |--index/
|               |--index.phtml
|             |--foo/
|               |--index.phtml
|               |--bar.phtml
|--public/
   |--css/
   |--images/
   |--js/
   |--.htaccess
   |--index.php

With this file structure, http://example.com/ should point to the public folder; this way, the application or the library can not be accessed through the browser, which improves security of the application.

The .htaccess file

The .htaccess file’s responsibility is to route requests to existing resources (existing symlinks, non-empty files, or non-empty directories) accordingly, and all other requests to the front controller. Example:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php

The bootstrap file

The biggest problem is setting up correctly the bootstrap file. Here’s an example of my bootstrap file, I use it on several projects, never had any problems :)

<?php
/**
* This is a general bootstrap file, change it to fit your needs
* Pay attention to the paths
*
*/
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors',1); // set this to 0 on live version

// This is my timezone, change it to yours
// See timezones here: http://www.php.net/timezones
date_default_timezone_set("Europe/Belgrade");

/**
* We need to set some include paths
* To the library
* And to the models
* And add it to the current include path
*
*/
set_include_path('.' . PATH_SEPARATOR . '../library' .
					   PATH_SEPARATOR . '../application/default/models' .
                       PATH_SEPARATOR . '../application/dummy/models' .
					   PATH_SEPARATOR . get_include_path());

include("Zend/Loader.php");

/**
* This little fella loads up a class when needed
* So we don't need to bother with including class files
*
*/
Zend_Loader::registerAutoload();

/**
* This config part is needed only when you
* store stuff for db connections in a .ini file
* I do it this way all the time, so it's a part of my general bootstrap
*
*/
$config = new Zend_Config_Ini('../application/default/config/db_config.ini', 'offline');
$registry = Zend_Registry::getInstance();
$registry->set('config',$config);

// Only needed if you plan to use layouts in your app
Zend_Layout::startMVC();

/**
* Get an instance of the Front Controller
* Tell him where to look for controllers
* And off we go!
*
*/
$frontcontroller = Zend_Controller_Front::getInstance();
$frontcontroller->throwExceptions(true);
$frontcontroller->setControllerDirectory(array(
        'default'   =>  '../application/default/controllers',
        'dummy'       =>  '../application/dummy/controllers'
        ));
$frontcontroller->dispatch(); // GO!!!

This kind of bootstrap file should be enough in most cases; it is for me.

This post is starting to get out of control, so I’ll stop here for now. Next time I’ll show some basic stuff with controllers, actions, views etc. Until then be sure to get familiar with the coding standard, especially with the naming conventions.

Hope that this text isn’t too confusing. I tried to keep it simple and explain all that is needed for starting with Zend Framework.

Any thoughts on ZF, or frameworks in general? Do you use any?

Share this post:
  • Digg
  • description
  • del.icio.us
  • StumbleUpon
  • Facebook
  • Reddit
  • TwitThis
  • Google
  • E-mail this story to a friend!
Other posts you might be interested in: Starting with Zend Framework - part 2, A Zend_Captcha example, Wordpress paging navigation, TickTweet WordPress plug-in, Wordpress as CMS tutorial, or just wonder on through the archives...
If you liked this post, you can buy me a cup of coffee!
Tags: framework, introduction, php, zend.
Categories: Development, Programming, Software.
Subscribe to the feed.

Comments: 24

Grab the comments feed

  • Cheeke

  • October 9th, 2008

I’m giving a try to PHP and PHP 5.3 looks very exciting with closures and namespaces, But I will not use any framework with PHP because PHP already is a web framework and template and it is easy to work with it as that way. For example the ZF framework I feel it bloats PHP , It makes hevyweight and difficult to use. I better suggest to apply best practices and Patterns in your programming and use plain PHP is the best.

I’m a Java programmer also and I love when we say it is a POJO a Plain Old Java Object it makes programming fun again and easy.

So I hope PHP continues the path of the easy to use and not get bloated and complicate as the EJB of Java it was hell to work with it.

Also I see a win win with PHP with Fast development cycle and it is a dynamic language is fun to work with, Before I bashed PHP a lot but now I’m getting to understand it.

Use plain old PHP object.

  • Luca

  • October 9th, 2008

Cheeke, do not forget there is no need to reinvent the wheel.
As far as I have seen, ZF is very loosely coupled, and together with autoloading, you can really just use what you need.
PHP lends itself well to non-structured code, which is its biggest problem and something ZF helps avoid.

  • Robert

  • October 9th, 2008

I forgot to mention that using a framework on smaller projects, especially ZF, is a bit contra-productive. Then plain old PHP objects are enough. But on bigger projects, that contains several modules, with more people involved on it’s development, using a framework is a good thing.

Sure, you can write your own classes, use it on your projects… But hey! That’s a kind of a framework — a set of classes which you use over and over again… Or you can use an already written framework. If it’s not enough for you, extend it. If it’s to big for you, take out what you need and what you want and use only that. I go with this second solution. I did write my own classes, used them, but in one moment I figured: “All of this is written before, 99.99% chance it’s written better, so why not use that?” This way I’m focusing on making the app and not on making the tools to make the app.

Heck, a carpenter doesn’t make it’s own hammer and saw, he goes to a hardware shop and buys them.

  • Rajkovaca

  • October 9th, 2008

Luca says: PHP lends itself well to non-structured code, which is its biggest problem and something ZF helps avoid.

You are 100% right on this one, and that will lead us to following question: How good can be any PHP-based framework if PHP itself can not be consider as a good base? PHP is tooooo loose on many things, there are no type checking and some easy way to debug your code, these and many other things missing from my point of view(btw. I’m C++ programmer :) )
Anyway, PHP has some advantages and who knows maybe it will evolve one day. I am sure that ZF represents a one step in good direction

  • Matthew Weier O'Phinney

  • October 9th, 2008

@Cheeke: ZF utilizes design patterns heavily, and is loosely coupled; you can use as much or as little of it as you want. If you don’t want or need a full-blown MVC application, you can still do things such as use Zend_Mail to simplify mailing (and allow utilization of an SMTP server), or Zend_Log to log your application (alternately with the FireBug log writer!), or Zend_Search_Lucene to index and search your site or documents. The main thing is that it, like any other good component library or framework, encapsulates code so that you’re not left re-inventing the wheel on each project you start.

  • mirko

  • October 9th, 2008

Can you post a links of projects which you made in zend framework?
This is stupid ” carpenter doesn’t make it’s own hammer and saw, he goes to a hardware shop and buys them”.
You don’t need to made a computer to make a website ….

  • Tims Blog » Blog Archive » NULL vs False vs 0

  • October 10th, 2008

[...] starting with zend framework [...]

  • Chirag Pinjar

  • October 10th, 2008

Good place to jump start Zend

  • Ivan Jovanovic

  • October 14th, 2008

Nice post about ZF, I’d just disagree on couple of things there, most within comments.

1. Carpenter doesn’t make its own tools. This is questionable since programming is about DRY principle, so why wouldn’t you make tools to leverage your productivity. ZF can help with this because it is from the start orthogonally designed and intended for decoupled architectures and also the tools that could boost your productivity can be design in the fashion to be non-invasive for the application developed and to be very reusable across projects, big as well as for small ones.

2. ZF is not suited for small apps. Well, under the light of the first point beyond there are numerous ways to be as productive as with some other, more rapid, frameworks but also to gain quality that comes with ZF as its intrinsic value. Just it takes some time for carpenter to make its own tools :)

Cheers,
Ivan

  • Robert

  • October 14th, 2008

Hi Ivan!

Thanks for the feedback, feel free to correct me or add anything you think I’ve missed :)

Under the term “tools” I was trying to refer to ZF itself. Looks like it wasn’t the best comparing, after all :)

For small apps (define small app as you like :) ), I feel that ZF in whole is big — this is my opinion. There are occasions when the MVC pattern and the Front Controller “thingy” are not needed, the job can be done with them, but is easier without them. Then a couple of light-weight classes are enough. I say again, this is my opinion.

Regards,
Robert

  • Robert Basic’s Blog: Starting with Zend Framework : Dragonfly Networks

  • October 15th, 2008

[...] Basic recently posted this introduction to the Zend Framework, a simple overview to how the framework is laid out and how you can get [...]

  • Marc Cools

  • October 18th, 2008

Hi,

I ‘m just learning php and good programming skills. Also learning good Englisch :)

I ‘ve read your post and dit some researce about Zend Framework. I like the structure thing. Bit I have two questings about this.

First: Why is the css in the public area? I thought that we limit the access to the public site for only entering the site and stuff that must be there to work (.htaccess). The css files are a part from the application. So I would espect it at views/skins/myVerryGreatSkinFile.css. Common ones could be placed at library/robertSkinMaster/. Commons like reset.css, InternetExplorerFixer.css, myFeel.css and so on.

Second: If a have for every entry a entryController.php in a module, what is the purpose of different modules? So a webuser is entering my site and index.php is executed. It pass control to indexController.php. This files calls the falls that are needed. Now an other user is entering through admin.php. So it will give control to adminController.php in the same module. What are the other modules for or why is every entry in the same module? I ‘m confused.

Maybe i ‘m plain stupid but I hope my very own software is very structured and only a setting is wrong. :)

Thanks.
Marc from Belgium

  • Marc Cools

  • October 18th, 2008

Add on:

- About css is also for js/ and images/
- Lots of typo’s, not only bad English.

  • Robert

  • October 18th, 2008

Hi Marc!

For the first question: (this may not be a precise explanation, but this is how I understood this part) the “public” folder with the CSS, JS and image files and folders is the document root of your application (well, it should be). It means that when you request the “www.example.com” page,the server serves you the contents of the “public” folder. Typing “www.example.com/../application/” in your browser’s location bar, will not show you the contents of the “application” folder; the server will just omit the ../ part and try to serve the “www.example.com/application” which doesn’t exist. Same goes for the CSS files: trying to include CSS files with “href=../application/deafult/views/skins/skin1/style.css” will not work; the server again omits the ../ part. All of this is for security reasons. However there is a workaround for this, here (http://p2p.wrox.com/topic.asp?TOPIC_ID=73382) is an example how to achieve this. But I would advice you to keep it this way, it’s much simpler.

For the second questions: think of a module as an application inside of an application. For example, you have a web site of some company on “www.company.com” in the default module. There they show their products and their services. One day, they want to add, e.g. a blog to their site. Now, you don’t need to mess with the default module, you just write a new module, the blog module, and your done. This way both modules have their own settings, administrator panels, etc.

Hope that these explanations made some things clear :)

Regards,
Robert from Serbia :)

  • Marc Cools

  • October 18th, 2008

Thanks!

I saw the light, wel … you switch it on. :)

  • Starting with Zend Framework - part 2 ~ Robert Basic

  • October 20th, 2008

[...] Starting with Zend Framework on October 7, 2008 [...]

  • colleen

  • October 22nd, 2008

I have a question about the config module, the legacy app I am converting had a bunch of config vars and sometimes it define one config var in terms of another one. For example there would be a general definition called ROOT_URL or something and then they would define a constant for IMG_URL which would bee ROOT_URL . “/images” How can u do this with php.ini or xml config file.

  • Approccio a Zend Framework : phpblog.it

  • October 22nd, 2008

[...] i propri progetti in PHP e trovandolo un prodotto adatto alle sue esigenze ha deciso di realizzare una breve introduzione panoramica al framework. Robert parla del pattern MVC, del coding standard proposto da ZF e di quanto sia utile aderire ad [...]

  • Robert

  • October 23rd, 2008

@colleen: Hi! I don’t quite understand what you want to achieve? What config module?

  • Colleen

  • October 25th, 2008

Well it looks like the new version of Zend Framework meets me half way. Apparently you can now
juxtapose bootstrapped definitions into values in the ini file or xml file and it has the machinery builtin to resolve them. In older versions people wrote all kinds of tricky convoluted scripts to do this, and to me it seemed to make things HARDER not easier. I am talking about the Zend_Config module. So you still have to do some pre-configuration before you actually read a config file, and typically these would be installation-specific values such as the domain / URL where the application is installed. I’m catching on now, thanks for the reply. One of the hardest things is making one of those apps like wordpress where you just press a button, tell it a couple of really obvious things and it creates installs and default configures everything for you. Next step to create databases from the script when the db is protected.

  • vasim

  • January 2nd, 2009

Hi,

I just start to learn zend frame work pls guide me that how i go ahead.

bye…….

  • Pinky

  • January 15th, 2009

I found the site very useful for begineers.

  • Nadar

  • April 2nd, 2009

Hallo Robert

Do you work as freelancer in your free time? If so, please contact me at my email address. I would like to diskuss a project with you, if you’re interessted in.

Just write me a Email.

Thanx
Nadar

  • Aryashree Pritikrishna

  • January 28th, 2010

Hello Robert,

First of all thanks a lot. Now I am beginner in ZF, your article help me a lot.

Thank you again,
Arya

Leave a Reply

 

Robert Basic © 2008 — 2010
Design & graphics by: Livia Radvanski
Coded by: Robert Basic
Home page last updated on November 30th, 2009.
Frameworks used: Zend Framework, jQuery, 960 Grid System
Blog is powered by Wordpress
Subscribe: Entries — RSS & Comments — RSS