Added by Gavin, last edited by Gavin on Jul 30, 2007  (view change) show comment

Labels

 
(None)

Introduction

In this tutorial, a tiny demo application will be constructed to highlight key features of the Zend Framework and demonstrate how its components could be integrated and used together. Although the demo application is not intended for production use, the working application provides a simple skeleton for building Zend Framework applications. Even advanced PHP developers may find some parts of the demo enlightening to see how the Zend Framework might differ from other frameworks in its use and application of design patterns and components providing popular functionality.

For those less familiar with MVC and frameworks, an ultra-light example is presented, before we begin building the forum demo application in order to avoid introducing too much complexity too fast.

What is the Zend Framework?

The Zend Framework (ZF) is a simple, straightforward, open-source software framework for PHP 5, and beyond, designed to eliminate the tedious details of coding and let you focus on the big picture. A large open-source community lead by Zend has invested enormous efforts to make the ZF a robust framework, suitable for both large and small tasks. A central goal emphasizing "extremely simple to use" is evident throughout the ZF, and has become one of the Zend Framework's key strengths. Similarly, the ZF gives preference to popularly recognized "best practices" through the use of many design patterns.

Why the ZF?

Several specific components in the ZF offer potential users true "gems" to enjoy and work with, including search, PDF, i18n/l10n, MVC, and more. Each offers "extras" and special features combined with ease-of-use making the ZF attractive for large team development efforts as well as individuals who have little time to spare and "just need to get the job done". The ZF adds new meaning to "done is beautiful" for projects completed using the elegantly architected ZF components.

Who?

For more information about the ongoing development and enhancements, please see the ZF Developers Website. The extraordinary ZF development community contains dozens of members from around the world, giving the ZF a wonderful internationalized "flavor". With the strong, continual backing of resources and support from Zend, the makers of PHP, the ZF's evolution continues at a reliable, solid, sustainable pace.

The Zend Framework is divided into [categorical groups] with [project teams] and mailing lists assigned to each of these groups.

Requirements

Another defining characteristic of the ZF arises from its ability to work without requiring unusual or non-standard PHP extensions. However, the forum demo in this tutorial is based on MySQL. Patches to support other databases are welcomed, but should completely replace code for MySQL, instead of adding code, since streamlined examples are easier to understand and follow by those reading this tutorial.

  1. PHP 5.1.4 or newer is required, but PHP 5.2.1+ is recommended, especially for production systems.
  2. MySQL 5 or newer is required for the forum demo, but not the introductory example in the next section.
  3. Web server like IIS, Apache, or Lighttpd and shell access with or without mod_rewrite
  4. Zend Framework 0.8 Official Release (not Subversion or snapshot versions) - Note: Until ZF 1.0 is released, this demo requires the latest subversion update of the ZF.
  5. Web browser that correctly supports both UTF-8 and XHTML (i.e. any recent version of the popular browsers).

Hint: For a speedy, less painful install of PHP, MySQL, and a web server see this list of Alternative Ways to Install a PHP Platform for ZF.

Installation of the ZF Demo Source

Make sure your web server has enabled the equivalent of Apache's AcceptPathInfo. This feature causes the web server to pass trailing URI parts to PHP for URLs like, "http://www.yourserver.com/index.php/trailing/URI/parts".

Make sure your system meets the minimum requirements shown above for this demo, and the Zend Framework requirements.

Download the Zend Framework stable release for this demo.

For more information about the ZF Lab, see "http://framework.zend.com/wiki/display/ZFPROP/Home". For those familiar with older versions of the ZF, you won't find the familiar "Zend.php" file. After approximately 2007-03-12, ZF 0.8dev and later replaces "Zend.php" with multiple classes, each containing logically related functions. This change simplifies organization of the ZF and checkout by containing all source files under "library/Zend".

Avoiding white screens

For development, blank white screens can be frustrating. Try enabling display_errors in your "php.ini" file. Also make sure to disable any caching software or output buffering on your server or in your application so that errors are not captured and hidden.

Ultra-Quick Install

For experts, and the impatient:

  1. Obtain the ZF library, the ZF Demo, and the ZF incubator.
  2. Configure your PHP include_path in php.ini, and enable AcceptPathInfo in Apache's httpd.conf
  3. Tweak "section1_install/config.ini" (and */config.ini for other sections you want to test)
  4. Create a MySQL database instance named zfdemo, username admin, password demo
  5. Copy "section1_install/index.php" to your website and test.
  6. Make backup copies of tweaked config files (e.g. config/config.ini.bak).
  7. Try accessing the copied index.php from your web browser.
  8. Install the "config/zfdemo.sql" into a MySQL instance, if the script above was unable to automatically install the ZF Demo tables and data.

Resume reading with "Testing Your Installation" below, or "Optional: Installation of ZF Library in Alternative Location" if you want to install the ZF library in a different location than described above.

Quick install using SVN

The ZFDemo comes in many, standalone parts named "sections" in this tutorial. Initial installation consists of downloading all the needed files, and organizing them for use by your web server and PHP. Afterward, installation of individual sections requires very little effort, since copying a single file to your web server's directory will "install" a chosen section of the demo.

The method below downloads and installs both the ZFDemo and the Zend Framework, but you need Subversion. For more information about using Subversion (and installing it on Windoze), see ZF Subversion Help.

Next, download the latest copy of the ZFDemo into your home directory:

Now, updating to the latest version of the demo is easy!

Resume reading with "Loading the Demo SQL Schema" below. Also see "Optional: Installation of ZF Library in Alternative Location", if you want to install the ZF library in a different location than described above.

Installing the Zend Framework without SVN

Not supported yet, since there is no download available without using SVN.

If you are not using Subversion (see above) to install the ZF, then after downloading, decide where to install the ZF. For the ZFDemo, the ZF can be installed by simply moving the "library/Zend" directory into the topmost directory in the ZFDemo (i.e. "zfdemo/Zend").

Resume reading with "Loading the Demo SQL Schema" below. Also see "Optional: Installation of ZF Library in Alternative Location", if you want to install the ZF library in a different location than described above.

Optional: Installation of ZF Library in Alternative Location

Alternatively, the ZF library could be installed in a location more convenient for sharing with multiple ZF applications. Use the PHP include_path to share a single copy of the ZF with multiple applications by listing the full path to the ZF "library" directory first. For example, install the Zend Framework library into your directory containing other libraries of PHP code:

Next, make sure PHP's include path lists "~/library" (or equivalent). Sometimes the "php.ini" file used by your web server is different than the one used by php on the command line:

Loading the Demo SQL Schema

In order to load the demo SQL schema into your database instance, first make sure you have an instance. Many web hosters provide a GUI administration web interface for this purpose. Use the name 'zfdemo' if possible, since the section*_*/config/config.ini files already have "database.name = zfdemo". If you need to use a different name, remember to change all these configuration files to the correct database instance name.

Hopefully most ZFDemo users will find simply copying section1_install/index.php to their web server provides a means for automatic setup of the needed ZFDemo tables by accessing that web page from their browser. If your browser shows you a dump of the tables, then skip to "Testing Your Installation" below. If not, then continue on with this section.

In the following section, various methods of using the mysql command are explored to help with loading the ZFDemo SQL schema into your database instance. Variations of the following will be presented and explained:

Check MySQL Connection

Next, try to connect manually to your database instance:

If the connection fails, check usernames, passwords, host names, and the database name. You may need to locate the "my.cnf" MySQL configuration file to determine how to properly connect.

Make sure you can access your MySQL database, before proceeding with any tutorial section using the database. If you choose to use a different name than "zfdemo", please substitute your name choice with "zfdemo" below and in the file "zfdemo/config/config.ini".

Verify access to database instance

Unless you have "root" or admin access to your MySQL database, please refer to your local system administrator or web hoster for instructions about creating a database instance or obtaining access to an existing instance. If possible, use a clean, empty database instance, so that all tables can be dropped and restored easily, without harming any important data already present.

If your database is configured to use a socket file, then replace "-host=127.0.0.1" with "-socket=<path>", where <path> is the socket file located and tested at the beginning of this section.

Installing the ZFDemo SQL Schema

If you have access to phpMyAdmin, then the SQL schema file "section4_mvc/config/zfdemo.sql" can be copied and directly pasted into the web page accessed via the "SQL" folder tab in phpMyAdmin.

Alternatively, the schema file can be loaded from the command line, as follows:

Replace "127.0.0.1" with the correct IP address or hostname for your database server. Also replace "zfdemo" with the name of your database instance above, and in any future example code snippets.

Testing Your Installation

The following tests help determine if the installation and configuration has succeeded.

Testing the Installed ZF

Now, make sure the following script outputs "Ready!".

Then, create a directory (e.g. 'zfdemo') inside your web document root (often "www" or "public_html") and copy the index.php file from "zfdemo/section1_install/index.php" into the newly created directory. This file is not really the demo itself, but only a testing script to help diagnose any issues that will prevent the real demos from running correctly. Each of the "sectionN_*" directories has a copy of the ZFDemo. Later sections have the same code as the previous section, but with more code added relating to the subject of the current section.

Lastly, try accessing this "index.php" from your web browser:

Installing the ZFDemo Test Script

Do NOT install the demo on a security-sensitive website. The demo is in rapid development, and may or may not contain a XSS vulnerability as a result of design goals placing higher priorities on training and education. After the demo has stabilized, the code will be reviewed for potential security issues.

After completing the initial installation of files (see installation sections above), to install the code discussed in each section of the tutorial, copy the single "index.php" file from "section1_install/index.php" to your web server's document root directory (e.g. "www" or "public_html"). As with all of the demo examples in this tutorial, the "index.php" file can work from within a subdirectory/subfolder. If you want to install the demo sections without affecting the rest of your website, you may optionally create a subdirectory, like "www/zfdemo", and then copy the "index.php" to this subdirectory. Using a ".htacess" file can improve security by restricting access, if the web server is not completely isolated/private.

After copying the file onto your website, make sure the demo code tree (containing section#_* subdirectories) is in the directory containing your web server's document root directory, which might be a symbolic link. For example, my home directory contains:

The "www" entry is a symbolic link to another location containing:

Testing the ZFDemo Install Test Script

To begin, the demo needs at least one piece of information - where to find the configuration information. The demo expects to find its source and configuration files in a subdirectory that is relative to the location of the "index.php" you copied as part of the installation instructions. There are many versions of this demo, with various features added. Each version is in a shared subdirectory. Thus, the demo looks in "../../zfdemo/$demoDir/". Hopefully, it won't be difficult to get the index file located correctly relative to the zfdemo subdirectory. You might have to adjust the first line of code in the "bootstrap" function in index.php:

If all works as expected, you should see:

Welcome to the ZF Demo Install Test

1. Continue Test
2. Online Tutorial


UTF-8 Rendering Test:

Umlauts and accented characters: many odd looking characters

more odd looking characters

Euro currency symbol
etc.

ZF Demo Debug Log

list of installed PHP extensions

various information helpful for debugging installation issues


Next Section: 2. Introduction to Model-View-Controller Architectural Pattern

The file Zend.php is missing.
The checkout of the library should be:
svn checkout http://framework.zend.com/svn/framework/trunk/library library

Also, it is not clear where to download the zfdemo directory.

Thanks! I updated the docs above. We are replacing Zend.php with different classes very soon.

Posted by Gavin at Mar 08, 2007 16:21

Hi.  It looks like you've put a lot of trouble into this tutorial, but it seems to have several bugs which I find fairly irritating.

 So - at the risk of betraying lots and lots of ignorance... (but that's why I came here to read a tutorial, isn't it?)... here are some problems I encountered:

  1. I tried using the "Quick Install with SVN", since I normally have pretty good results with svn, even if I'm not an SVN guru.  But svn did not allow me to checkout Environment.php, because it is a file, not a directory (neither svn in Eclipse nor command line svn allowed this - I'm using svn versin 1.4.2).  OK, so I got it checked out by checking out the directory elsewhere and then moving the file, but still...  
  2. The path for checking out the Environment directory is not quite right.  It should be "... incubator/library/Zend/Environment ", not "... incubator/library/Environment " (the Zend directory is missing).
  3. The last paragraph in the "Quick Install with SVN" paragraph is rather useless, or am I missing something here? As a ZF newbie, I don't frankly know what to do with this information about the Zend.php file, and I have the sneaky feeling that I don't care.  And the URL takes me to the Zend Framework Proposal Process - if I was ready to make proposals, I wouldn't be reading Section 1 of the tutorial, would I? Or am I missing something here?
  4. Which section should I start with? More precisely, from which section should I copy the index.php file? I would have thought I should start with Section 1.  This is Section 1, right? And in the Section "Testing Your Installation", that was the file I was told to use.  But then suddenly there's talk about "Installing the ZFDemo Application", where it says to take the index.php from Section 4! 4 comes before 1?
  5. Or can I skip "Installing the ZFDemo Application" does the "Quick Install with SVN" make that section unnecessary or not? In other words, there seems to be two alternatives here: Quick Install or (Slow) Install.  So, where does the 2nd alternative end and the main line of your text resume? In still other words, where should the reader who chooses the quick install resume reading?
  6. So, as I noted above, I copied the index.php from the section 1 install file, adjusted the line explaining where the section1 install directory is - and did not get anything like what I "should see" ... "if all works as expected".  I got an uncaught exception since I haven't configured the framwork to know where my MySQL is.  Duh.  I could probably go on and do that now, but as a timid newbie, who still has this nagging feeling that perhaps I really should have installed the index.php from Section 4 (not Section 1 - see above), I decided to add this comment to vent my frustration instead.
    So, please go easy with us poor tutorial readers.  Little confusions like that can chase away people who would otherwise use the Framework happily.  After all, the main reason I'm trying to learn the Zend Framework is because I got so fed up with bugs in the CakePHP tutorials that I threw in the towel over there!

Thanks Ronald, this list was helpful, and I've updated the relevant text and code for each item you listed

Posted by Gavin at Apr 02, 2007 18:52

You're very welcome.

And this chapter is definitely better than it was. Good work.

I can't say how someone who hasn't seen the old version will find it, not being sufficiently "innocent" any more, but it seems better to me.

One small complaint - the sentence "Make sure your system meets the minimum requirements for this demo" includes a bad link - right back to this page! Makes you feel like someone's trying to mess with your mind when your browser jumps to the top of the page and makes it obvious - if not immediately so - that you're no closer to the minimal requirements than before...

One rather tentative suggestion: After tweaking the dot-ini file, I finally got almost the output shown (or rather, described) in the tutorial - but it took a while before  I got the right output.  It turns out that short_open_tag was turned off in my php.ini. Weird that I hadn't noticed that yet... Whether you want to mention that in the "minimum requirements" (or somewhere else) is, of course, up to you.

Anyway, once I figured that out, I got the output I was expecting. So now I've moved on to Chapter 2, which was quickly finished, and am just taking a moment before going on to Chpater 3.

Keep up the good work!

P.S. I'm not sure if the new section on "Alternative LAMP Stacks" is a good idea, since it's too short to really handle the subject well, and expanding it would eventually be a major distraction from the tutorial. I'd suggest replacing it with a good link, perhaps to somewhere in php.net. That said, if you are going to keep it consider adding a link for PHP 5 for us MacOS users. I'm using PHP 5 from entroy.ch - see http://www.entropy.ch/software/macosx/php/. I'm told MAMP is also quite good, but haven't tried it myself - see http://www.mamp.info.

Thanks again. I am removing the requirement for the php short open tag .. will commit changes soon to SVN. I fixed the link, and moved the WAMP/LAMP/MAMP section to its own page.

Posted by Gavin at Apr 12, 2007 20:45

If I comment out this code, everything runs fine:

If I leave it in I get this (I added an echo to find the error):

Hello Gurus,

Please I'm just a bit new here in ZF, I'm trying to learning it. This tutorial seems to be the right one for me. But I've a problem. I realy realy don't know how to donwload the zfdemo package. Please can you help me with this? (if it is possible send me a link where can it be donwloaded as some packed file) I do not want to use some svn, cvs alen something similar. Is it possible?

Thank you very much.

Best regards,
Michal

Posted by Alef at May 15, 2007 08:52

Perhaps the "Requirements" section should be a little more detailed?

I found I needed the following adding on my own system (Debian stable - etch, using PHP 5.2.0):

pdo_mysql extension (pecl install pdo_mysql)
php5-dev for phpize as the above failed without it (apt-get install php5-dev)
libmysqlclient15-dev as pecl failed again without the mysql header files (apt-get install libmysqlclient15-dev)

After this, I then hit the same error as Wayne D. Roesner above (on Mysql 5.0.32-7), and I still hit it even after pulling Debian's testing version of MySQL 5.0.38-1 so finally gave up and took Wayne's advice to bypass it by commenting out the code, and instead, I ran the SQL manually with mysql zfdemo /section1_install/config/zfdemo.mysql.sql. Now I get the Demo Install Test page.

Must admit I'm curious as to why this last error comes up. I am using a MySQL 5.0 after all. PS. My PHP is

Apols. Please ignore the PS above! I mentioned the version PHP version already anyway.

Hi Guys,

I set up the demo environment, but when I open section1_installs directory index.php (I copied the document root) I've got the following error:

Fatal error: Call to undefined method Zend_Config_Ini::asArray() in /var/www/gentoo.terem1.hu/htdocs/zfdemo/index.php on line 111

What I missed?

Sorry, my include_path was wrong. After I set up include_path correctly I've got a next error:
Fatal error: Cannot redeclare class Zend_View in /usr/local/apache2.2.2/Zend/View.php on line 36
Where /usr/local/apache2.2.2/Zend contains the Zend Framework from svn.

I am having the same problem.
Is this demo working with the current version 1.0.0 or is it outdated?

Posted by Tilman at Jul 09, 2007 11:43

It really seems not to work with 1.0.0. After sorting out the asArray()-Problem (replace all occurences with toArray(), I get the error:

Fatal error: Cannot redeclare class Zend_View in /Applications/MAMP/htdocs/commons/Zend/View.php on line 48

It's really hard to find working 1.0.0-Tutorials out there, but I found this one to be working:
http://akrabat.com/zend-framework-tutorial/

Regards,
dasicebaer

To get it working with ZF version 1.0.2 I did the following after getting the sql schema into my database.

1. Change all of the asArray calls (the error messages have the line numbers in) to toArray as stated by dasicebaer.

2. Find where it says: require "Zend/View.php"; mines on line 166 in index.php and change it to require_once.

3. Then an error message appears about a missing index.phtml file, go to the zfdemo/section1_install/default/views/ directory, in there is a file called indexIndex.phtml, create a directory called scripts here and inside it create another directory called index. Now inside this place a copy of indexIndex.phtml and rename it to just index.phtml so you have zfdemo/section1_install/default/views/scripts/index/index.phtml

Cross your fingers and on a good day, with a following wind Robert will turn out to most definitely be your Mother's brother (aka Bob's your Uncle).

It worked for me, ymmv.

Cheers
Amos

Then clicking on Continue with test brings up a similar error involving the forum directory. Add scripts/index/ to zfdemo/section1_install/forum/views/ and move/rename indexIndex.phtml from this directory to the newly creatd one to continue.

Cheers
amos

Although I am now getting errors:

Warning: Invalid argument supplied for foreach() in C:\Apache2\zfdemo\section1_install\forum\views\indexIndex.phtml on line 40

for each table.

Then it claims that

ERROR: No tables found!

and four counts of:

Notice: Undefined variable: table in C:\Apache2\zfdemo\section1_install\forum\controllers\IndexController.php on line 51

Well I'll come back another time and try and find my way through these.

Cheers
Amos

To solve the first warning:

In line 48 in zfdemo\section1_install\forum\controllers\IndexController.php: replace
"foreach ($this->_db->query($q) as $row)" with
"foreach ($this->_db->fetchAll($q) as $row)" or use the MySql-specific method listTables():
"foreach ($db->listTables() as $row)" (and skip array_pop in the next line).

The second warning comes because the $this->tables has not been populated (by IndexController.php) the second time the view file "indexIndex.phtml" is rendered. So indexIndex.phtml returns with an error warning.

I haven't yet figured out why "forum/scripts/index/index.phtml" is needed at all - it seems like a mistake that the same view file is needed in two places (also in "forum/indexIndex.phtml") and why both of them are called...?

I begin to suspect that Gavin has left us with some pedagogical bugs to allow us to solve and learn

All the best,
Marc

Oops, I mixed up two places. The listTables() method could be used in the zfdemo/index.php file at line 350. Both the "fetchAll" and the original "query" seems to work here too. I thought it was causing a bug before. Sorry for confusing.

All the best,
Marc

Hello There,

I use a bad hosting service so, they tell me that PDO is not available. HERE you cant find how to meke this work with MYSQLi

1. Add to config.ini
db.adapter = MYSQLI

2. Comment this line (search bewtween 150 and 160)
//$db = new Zend_Db_Adapter_Pdo_Mysql($config->db->toArray());

3. Add this line after the last one
$db = Zend_Db::factory($config->db->adapter, $config->db->toArray());

4. Comment and add this
//self::testDb($db); // sanity check connection and zfdemo tables using Zend Db Adapter PDO
self::testDbi($db); // sanity check connection and zfdemo tables using Zend Db Adapter MySQLi

5. Copy the function
private static function testDb ---> private static function testDbi
(I mean, copy all the content and change the name)

6. In the new function comment this
//$db->query($sql);

And that all. Now you can run the tutorial with Mysqli.

Hope help someone.

Bye.
Agustincl.

I'm finding the install instructions a little vague - possibly written for experts, by experts. Right now I have parts of zfdemo off my apache docroot, plus a copy at the same level as the docroot. I'm not sure what I should have.

I'm getting this error when I try to test "zfdemo/section1_install/index.php"

Warning: parse_ini_file(\config.ini) [function.parse-ini-file]: failed to open stream: No such file or directory in D:\Common\ApacheDocroot\zfdemo\Zend\Config\Ini.php on line 106

Fatal error: Uncaught exception 'Zend_Config_Exception' with message 'Section 'sandbox' cannot be found in \config.ini' in D:\Common\ApacheDocroot\zfdemo\Zend\Config\Ini.php:152 Stack trace: #0 D:\Common\ApacheDocroot\zfdemo\index.php(112): Zend_Config_Ini->__construct('\config.ini', 'sandbox', true) #1 D:\Common\ApacheDocroot\zfdemo\index.php(38): ZFDemo::bootstrap('D:/Common/zfdem...') #2

Unknown macro: {main}
thrown in D:\Common\ApacheDocroot\zfdemo\Zend\Config\Ini.php on line 152

Anyone know how to get it working?

You need the following structure:

  • library
    • Zend
      • Acl
      • Auth
      • ...
  • zfdemo
    • doc
    • section1_install
    • section2_...
  • htdocs/www/public_html (document root)
    • zfdemo (place index.php files of your current lesson here)
      • index.php

After finishing this you should get the above mentioned errors