A Complete Beginner’s Guide to Zend Framework: First Steps

Getting into Zend Framework: First StepsYou’ve been still tormenting and write-ins of the same type in the n-times for the site? You do what has been done for you and try to divide the project design from the code? Looking for realization of the necessary functions in questionable forums? If you answered “yes” one of these questions, so this article is definitely for you. There I will tell you about the powerful free framework (Content Managment Framework), if you learn it you will not only save time for the design, but also rtake the quality of your work to a much higher level. So, let’s sit comfortably and read my first article of the series “Learning to work with Zend Framework”.

Why to use Zend Framework?

The major aim for any CMF – reduce time for a project’s working up. Using this product, you can achieve following:

  1. Permanent structure of your projects. The problem of majority projects, making from nothing, – absence of a permanent structure. First, you put necessary function in one module, in the next project you realized you’d made a mistake and decided to change everything. As a result, the more you create a website / web-applications, the more you improve your knowledge, well then you make changes in the structure of new projects. But now try to imagine that you will have to go back to support/revision of your oldest project. I’m sure you’ll just get entangled or waste much of time for the code’s investigation. When you create a web-based application frameworks, this problem disappears, because you’re always guided by rules. This approach can guarantee that, if the oldest project’s revision is necessary, you will always know its structure and can finish it off easily.
  2. Increase the speed of development. There is a set of classes in ZF that allow to realize a lot of typical actions. You’ll not need to create one more bicycle cause you have the whole Kamaz of ready-made bicycles.:)
  3. Increase the level of safety. Everybody makes mistakes and no one is safety. It is difficult to argue, but with the help of ZF you can significantly reduce the error rate in the project. Because it’s really to make a lot of typical actions with the help of built-in classes, it means you have to write less code. And less code, less errors.

Is It Difficult?

Someone says that ZF is too complicated for understanding, heavy, requires a lot of server resources. It’s not like this in reality. If you can to learn php, so moreover you can deal with ZF, and as for heaviness, a good diet will eliminate this shortcoming with no problems.

Positive and Negative Of ZF

There are no ideal solutions and ZF is not the exception. It has its both positive and negative sides, which we’ll discuss in this part. Let’s start with the negative:

  1. Heavy, version 1.8.a for exaple is 17 MB (well, not be afraid of), although this is not so much. If you’re scared this size, see the size of many commercial CMS. Almost of them rolled over for 10 MBs and it is not surprising, cause they have a lot of functions. It is the similar story with ZF. It provides a lot of opportunities, but it’s not the fact that you can use them all.
  2. Requires a lot of time to study. Actually, this all is individually here. Some may mark time a year, while it will be enough for others just a few days and they are ready to write their first applications.
  3. Resource-intensive. To be honest, I have not seen more than one hosting provider that would kick the bucket from ZF.

That’s all the negative sides. Now the positive:

  1. ZF is a set of classes, most of which are not tied to each other, so that it can be used as the spare parts in other projects and completely. There is all you need in today’s Web projects.
  2. The presence of a component to work with third-party services.
  3. Object-oriented approach.
  4. MVC pattern based.
  5. Well documented.

So, it’s enough, no more theory and let’s go straight to practice. We estimate the possibility of the giant, so to speak:) Inorder to work with ZF, we need ZendFramework (you can download the latest version from here, HTTP server with the mod_rewrite support, PHP at least version 5.2, and MySQL 5. Download the latest stable version. By the way I almost forgot, you can download ZF in two different assemblies:

  • Full
  • Minimal.

Full Package contains the Dojo Toolkit, and the demos to work with a skeleton. Because you are just beginning to study this framework, I recommend to download this version.

Minimal Package contains only ZendFramework library.

Extract the folder with the core (/ library / Zend), ZF is better to keep a few levels higher, so that don’t produce the files for each project, in my example, it turned out in this folder D: \ library \ ZF \ 1.7.8 \ Zend \. (i’m on PC)

Making the Structure of the Project

Let’s organize the file structure for our future project. Create two directories in the root of the application:

  • application – here all our software modules of the project will be stored
  • public, where will be available all share files.

Also create index.php and .htaccess in the root, in which immediately add rules of redirects:


RewriteEngine on
RewriteRule .* index.php

It’s necessary to add similar .htaccess file, in the folder “public”.


RewriteEngine off

Now lets create 3 folders in “application” directory: configs, library, modules.

  • configs — here is configuration files of the project.
  • library — for additional libraries.
  • modules — and it’s for modules of our application.

After all these simple manipulations I had such a structure:

The root:

  • application
  • configs
  • library
  • modules
  • public
  • .htaccess
  • .htaccess
  • index.php</li

If the structure is ready, so we can move on to the coding ;-)
Open our index file (index.php). Let the interpreter know that php code wiil start soon and determine 4 constants:


PATH_TO_ZF - the path to ZF
PATH_TO_APPLICATION - the path to the folder “application”
PATH_TO_LIBRARY - the path to our libraries
PATH_TO_MODULES - the path to our modules.

The code:

define('PATH_TO_ZF', '../../../ZF/1.7.7/');
define('PATH_TO_APPLICATION', './application/');
define('PATH_TO_LIBRARY', PATH_TO_APPLICATION . 'library/');
define('PATH_TO_MODULES', PATH_TO_APPLICATION . 'modules/');

Now we should tell our intepriter the path to load all our stuff from:

include_path(PATH_TO_ZF . PATH_SEPARATOR . PATH_TO_APPLICATION . PATH_SEPARATOR . PATH_TO_LIBRARY);

The next step is to download Zend_Loader (later we will return to it) and register classes’ autoload.

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

So, Zend_Loader is loaded, now let’s activate Zend_Controller_Front (about it, too, later) and point the location of our modules to the dispatcher. Then start the process of dispatching.

$controller = Zend_Controller_Front::getInstance();
$controller->addModuleDirectory(PATH_TO_MODULES)->dispatch();

The result should be something like this:

define('PATH_TO_ZF', '../../../ZF/1.7.7/');
define('PATH_TO_APPLICATION', './application/');
define('PATH_TO_LIBRARY', PATH_TO_APPLICATION . 'library/');
define('PATH_TO_MODULES', PATH_TO_APPLICATION . 'modules/');

set_include_path(PATH_TO_ZF . PATH_SEPARATOR . PATH_TO_APPLICATION . PATH_SEPARATOR . PATH_TO_LIBRARY);

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
$controller = Zend_Controller_Front::getInstance();
$controller->addModuleDirectory(PATH_TO_MODULES)->dispatch();

As you can notice Zend_Controller_Front never loaded because Zend_Loader loadsController automatically. Zend_Loader recognizes location of the controller on its name:
Zend_Controller_Front is in Zend/Controller/Front.php

A Little Bit More About Controller

Zend_Controller_Front implements the Singleton pattern, that means it can be initialized in the project only once. When you call a method dispatch(), the manager goes into a loop of dispatching passing three events:

  1. Routing defines what module, controller and the event can be called. If other ways are not written, then: site.ru/modules/controller/action/var1/value1/var2/value2 /. You can also override the paths through Zend_Controller_Route, but more on that in the next article.
  2. Dispatching – checking for the called module, controller, and events and call events.
  3. Answer – the view rendering.

Developing our Module

Create the folder “default” in our modules folder, it will be our first module. If we turn to our website using the link http://localhost/site.ru (you may have another location), it will be carried our default module. Name of default module can be changed, for example, to the “index”. It is done using the method – setDefaultModule (), object Zend_Controller_Front. It’s necessary to call the method before dispatching. As a parameter the method should get the module name, which will be used by default.


$controller->setDefaultModule('index');

Come on. We will create now two more folders in the module’s folder:

  • controllers — there are module controllers
  • views — but here everything related to the view (presentation)

Create a new controller (IndexController.php), and put this code:

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
return;
}
}

Now you need to create a script for our controller. For it, create folders “scripts/index” in a folder “views”. It should be something like this:


default
controllers
IndexController.php
views
scripts
index

Create a file index.phtml in the folder views/scripts/index/. Try to test it! If there are no errors, it means you are good to listen to me :) Now add the event:


$this->view->var = ‘ZendFramework’;

General view of the controller looks like this:

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$this->view->var = ‘ZendFramework’;
}
}

Lets add into the view file the following code:

echo $this->var;

After that, update the page.

Creating an Error 404 Page

Create another controller in our module, ErrorController.php:

class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
return;
}
}

Now lets create a submission for the error: /default/views/scripts/error/error.phtml:


404

In order to test it, type in your browser’s address bar: site/qwerty. As we do not have this page, so the result will be appropriate. In order that would include the output error due to which the script is stopped before dispatching we need to call the throwExceptions() method and passing the appropriate parameters, if we want to see a mistake, true, and false, if we want to differentiate a mistake when we created this page.

You’re Done!

First, I think that’s enough. For our first meeting we discussed a lot of interesting things. It is not all clear while, but do not worry. Skill comes with time. The main thing is not to be lazy and try to do something. In the article I mentioned that ZF is based on the MVC architecture. If you’re scared or have entered a dead end, the words “view”, “controller”, then launch Google and read a basis MVC theory.

That’s all; I hope you enjoyed this tutorial, and thanks for reading! See you in next chapter.

Nick Plekhanov

Hi there! My name is Nick Plekhanov. I'm a passionate web developer and user interface designer from Russia, experienced in PHP, and MySQL along with the beautiful XHTML and CSS under jQuery stuff. I've been doing web development for 3 years. Here, I'll be your PHP coder, sometimes designer, and SEO expert. My own web development blog is coming really soon. If you’d like to connect with me, follow me on Twitter.

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. sarmen says

    i wish this article had better grammar. It was really hard to follow along; but thanks for posting

  2. Artur Ejsmont says

    Good stuff

    Once you get going it can be worth to stop for a moment and have a think where do things go? how to separate concerns? how to decouple the layers and identify rules of what should be done and in which place.

  3. Rajeev says

    Hi ,

    i have followed your steps,
    I got this error:

    Fatal error: Uncaught exception ‘Zend_Controller_Exception’ with message ‘Invalid controller specified (error)0′ in C:xampphtdocszendrajapplicationlibraryZendControllerPluginBroker.php:337 Stack trace: #0 C:xampphtdocszendrajapplicationlibraryZendControllerFront.php(965): Zend_Controller_Plugin_Broker->postDispatch(Object(Zend_Controller_Request_Http)) #1 C:xampphtdocszendrajindex.php(15): Zend_Controller_Front->dispatch() #2 {main} thrown in C:xampphtdocszendrajapplicationlibraryZendControllerPluginBroker.php on line 337

    can u please help me in it?

    • says

      Hi, I’m not sure the author of this guide can answer your question since we’re no longer in contact with him. I suggest you post this problem on Stackoverflow and other QnA sites for webdevelopers. I’m sure you’ll get fast feedback.

  4. r-benTahir says

    now i got the idea how thing goes under the hood.. very well explained.. thumbs up for this.. now i think zend should come with the smarty.. hell it will make things lot easier.. regards. :-)

  5. says

    Any reason you are not using 1.10? 1.11 is right around the corner. Also after 1.8, ZF started using Zend_Application_Bootstrap to help get your application loaded, which would be much easier for noobs, instead of writing all this custom code in your index.php.

  6. Dave says

    oops, I cannot type the signs it ends with. Anyway, looks like there is an error in your html.

  7. Dave says

    So, does this mean your manually generated structure looks the same like the auto-generated structure by zf?

    btw: by the way: Your directory structure looks like it is one level only, and it ends with </li … so there might be a coding error in your html.

  8. oscar B. says

    Hi, Excellent tutorial (i will read the 2nd part in a few momements :).

    Im currently trying to learn Symfony. What do you think of it? I would appreciate your guidance!

  9. Rahul says

    i would hire a professional to do all that to me , haha , i didn’t actually have time recently to learn these kind of things , i know it make sense and it really helps , but may be soon i will !! :)) thank You

  10. says

    I don’t use to do these stuffs manually . We have the zf command line from 1.8 onwards . So why do we want to mess with all :) .
    The things that you have done can be done via

    $zf create project

    The default structure and the error controller and all will be done :) .
    Need to create another controller ?
    $zf create controller

    Need to create another action ?
    $zf create action

    Like so and so :) .

    • Nick Plekhanov says

      Thanks. Good addition Hari K T – I totally agree!
      Just wanted to show how to do things without them ;)

      • Gopal Aggarwal says

        Actually Nick, I think the tutorial would have been better for beginners if we used the command line tool. And this manual process could have been something of an extra, for the motivated reader to understand in more detail.

  11. says

    “Resource-intensive. (…) I have (…) seen more than one hosting provider that would kick the bucket from ZF” – well, that makes it even more odd that provider 1&1 is -to my knowledge- offering Zend framework within their shared hosting environment. Has anyone experience with ZF on 1&1 shared hosting servers? Last time i looked, they themselves didn’t offer much/any documentation on the subject. So if anyone could point to a decent “Hello World using Zend framework on 1&1 servers” tutorial that would be much appreciated.

  12. Nick Plekhanov says

    Looking forward to your feedback, comments, and opinions on what should i do to improve my article’s usefulness for you my friends.

    Thanks

  13. Mia Lazar says

    I like PHP frameworks but ZEND looks for me much more complicated until now, thanks.

  14. says

    Thank you so much for this.

    I was looking for an article just like this about 3 weeks ago, and now I’ve found it!!

    Better late than never :-)