U bent hier

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

afbeelding van globecom

 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

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.

Onze klanten

From the blog

afbeelding van globecom
afbeelding van globecom

Changing next number in a Drupal serial field

After searching for 2 days on Drupal.org without finding a good way to change the starting point of a serial field I

Read more...
afbeelding van globecom

Automatisch PDF maken, mailen en toevoegen als bijlage

Voor een klant had ik de uitdaging het volgende te maken.

Read more...

Neem contact op

  • Globecom
          Schoolstraat 245
          7606EM
          Almelo
  • +31 (0)634924795
  • info@globecom.nl

Laatste Tweets

Latest Shots