<

Starting Zend Framework

Published on
9,536 Points
2,936 Views
1 Endorsement
Last Modified:
Approved
After developing some projects with Zend Framework for three years, I decided to share some of my experience by writing this article.  I  hope it helps someone out there :)   Please do not hesitate to contribute by posting your own comments after the article.

Like most of the other frameworks in PHP, ZF implements most of design patterns with great success and has a huge development staff that really works well in a rapid development environment, etc.   But those are not the subject of this article.
 
In this article, I'll try to explain the basics of the framework.  I have to confess that at the beginning of my ZF workout, I was almost giving up.

We should always remember that unlike most of other frameworks we can use ZF components separately without implementing the framework completely, but we will have a look at basic requirements that we need to use framework in its full functionality.

ZF works with MVC design pattern (if you ask yourself what it that? don't commit suicide... it basically separates database operations, interface development, CSS, HTML, JavaScript, etc., and the development language that handles process between models and views to create dynamic content which is completely based on URL.
 
If we have a look at ZF-based project, we will realize that we point the related controller in our browser address bar.  In addition to that, ZF looks for the related section in that controller as an action in URL.  For example:

    http://localhost/Controller/Action 
in a real life project, we may consider as...
    http://localhost/Index/login

Each controller is a class that extends Zend_Controller_Action with appendix of "Controller" and each action is a method in that class that takes appendix of "Action" , so we should imagine as:

    class IndexController extends Zend_Controller_Action {
        public function loginAction() {
            // login related operations triggered from here
        }
    }

Open in new window


1) Enable mod_rewrite

Due to the URL-based build of ZF, first we must enable mod_rewrite  in our web servers, for Apache / Linux users, it is as easy as:

    sudo a2enmod rewrite

Then changing "allowoverride" directive to "all" from http.conf or the default file from "sites-available" will let us use the .htaccess file, so again we need this to use http://localhost/Controller/Action URL build.  Here is a working .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]

RewriteCond %{REQUEST_FILENAME} -d

RewriteRule ^.*$ - [NC,L]

RewriteRule ^.*$ index.php [NC,L]

RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php

Open in new window


2) Installing ZendFramework (Do not run!! we ll just copy some folders :P )
 
In fact, this is the easiest part .  After downloading ZF from http://www.zendframework.com/
just upload the Zend folder to your web server and add the path to "include_path" directive in php.ini .

While your php.ini is open, let me add something:  The basic Zend framework folder build is something like ;

  Applications /
        controllers/
        models/
        views/
                scripts/
                        layouts/
        config.ini
  www/
        .htacccess
        index.php

So if we add those three main folders to include_path we won't have to deal with requiring include operations in our project...  although some experts insist that this is an optimization fault, I don't care at all :) .  For example:

    include_path = ".:/var/applications:/var/applications/controllers:/var/applications/models"

I usually upload the Zend folder under the models directory, so I don't need to re-type inclusion directive for it in that case.
 
3) Let's have a look at our index.php aka bootstrap file

I am not sure why people try to give complex names to such files anyway it is index.php for me here is a working sample :) ;

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload() ; # __autoload() magic function used in ZF 
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true); 
$frontController->setControllerDirectory('/var/applications/controllers');

$section = getenv('PLACES_CONFIG') ? getenv('PLACES_CONFIG') : 'live'; # We parse the live section of our config.ini file 
$config = new Zend_Config_Ini('/var/applications/config.ini', $section);  # We call our config.ini file
Zend_Registry::set('config', $config); 								   # And save it in config var
Zend_Controller_Action_HelperBroker::addPrefix('Cal_Helper'); 
$layout = Zend_Layout::startMvc('/var/applications/views/scripts/layouts'); # Two step view pattern implementation starts here , also we can assign layout name as first parameter otherwise it will be [layout].phtml as default

$db = Zend_Db::factory($config->db->adapter, $config->db->config->toArray()); #Connecting to database
Zend_Db_Table::setDefaultAdapter($db);						                     #Setting default database adapter
Zend_Registry::set('db', $db);	#We populate $db var 
	try {    ## And we dispatch here
		$frontController->dispatch(); 
	}
	catch (Exception $exp) {
		$contentType = 'text/html';
		header("Content-Type: $contentType; charset=utf-8");
		echo 'Unexpected Error :';
		echo '<h2>Hata: ' . $exp->getMessage() . '</h2><br /><pre>';
		echo $exp->getTraceAsString();
	}

Open in new window


Also, here is a working config.ini example:

[general]

db.adapter = PDO_MYSQL
db.config.host = "localhost"
db.config.username = "usernamehere"
db.config.password = "passwordhere" 
db.config.dbname = "yourdbnamehere"

[live : general]

[dev : general]

[test : general]

Open in new window


As you see, ZF has cross-database support.  Also, you should need an .htaccess file.

To summarize:

1) Enable mod_rewrite ,set allowoverride directive to on, check mysqli extension if you will use mysql as DB adapter.
2) Build your folder structure, upload Zend directory, create your model,view,controller directories, configure your include_path
3) Create your index.php,config.ini and .htaccess files

It seems a little complicated, but when you start to use, it is worth all the mess, accelerates development  by %60 and makes your project sustainable, robust and easy to develop.
1
Comment
Author:Ali Kayahan
0 Comments

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Join & Write a Comment

Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Other articles by this author

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month