Thursday, July 9, 2009

Joomla component in Zend Framework example

Joomla is a nice CMS(content management system) and Zend Framework is once of the famous and widely adopted MVC Framework since its first release. One of the nice thing about Zend is its loosely coupled components.

Keep in mind that component in joomla and Zend Framework don’t refer to the same concept. Those who have worked in Joomla and Zend Framework know the difference.

In this article I’m not going to discuss what Zend and Joomla are all about and how component is different in both, but instead I’m going to share a little secret of how to develop joomla component in Zend Framework.

This article is not for those who are unaware of joomla and Zend.

Although joomla has own API for developing its components and modules, but you can use any php code in addition to its own API.

Reason is simple. Joomla is developed in php.

As Zend also used php behind the scene, so both can interact easily.

This was a bit of introduction.

While discussing all these things I assumed that you have little knowledge of joomla and have some knowledge of Zend Framework as well.

So let’s dig in.

Before writing any code you will need to successfully download and install joomla. Also download Zend and save it in the directory of your choice.

Once successfully installed joomla, open joomla/administrator/components and create a folder called com_yourcomp.

This is your component folder. You will need to create a file named yourcomp.php

If you want to add component in your administrator, the name should be admin.yourcomp.php.

That’s it, you have now created a the necessary directory structure for your joomla component development.

If you write a line “Hello world!” in youcomp.php or admin.yourcomp.php and browse your page as

http://localhost/joomla/index.php?option=com_yourcomp

you will see

“Hello world” printed.

These are the minimum requirements for developing joomla component.

Now we will using Zend Framework classes to add code to this file plus we will create Zend directory structure in order to work with Zend MVC.

Create following directory structure in your joomla/administrator/components.


Here you can see that my component name is com_advertisers.

In this directory I’ve

* admin.advertiser.php file
* application directory
* Joomla directory

The file admin.advertiser.php will serve as the bootstrap file.

Application directory contain specific directory for controllers, models and views.

The most important role is played by our Joomla directory in developing joomla component in Zend Framework.

This directory contain Controllers/Plugins/Router.php file.

This file contains code for calling specific action based on particular task. Before going to discuss code in the Router.php file, I’m going to show the code need in our admin.advertisers.php file.
<?php
define('ROOT_DIR', dirname(__FILE__));
set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/'
. PATH_SEPARATOR . ROOT_DIR . '/application'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . get_include_path()
);

require_once "Zend/Controller/Front.php";
require_once "Joomla/Controllers/Plugins/Router.php";

$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);

$frontController->registerPlugin(new Joomla_Controllers_Plugins_Router());
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');

$frontController->dispatch();

In the first few lines I have included path to our com_advertisers directory, application directory and models directory.

Next I include Zend Front Controller files and Router.php file. I’ll discuss code in the Router.php file later as it contain the most important code.

Next I initialize front controller, register Router Plugin class which is defined in our Router.php file, set controller directory and call dispatch.

That’s it. We have now defined our bootstrap file.

One important thing is setting path to our library files that contain Zend component.

You can include path using set_include_path or set it in your php.ini file.

If you don’t include this path, your application will not work as you expected.

Now go to controllers directory and create IndexController.php and write the following code in it.
<?php

require_once('Zend/Controller/Action.php');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function editAction()
{
}
public function saveAction()
{
}
}

Noting special here. I’ve created only three actions.

Go to your application/views/scripts directory and create directory called index and create three files index.phtml, edit.phtml and save.phtml.

The code above is what you will need to work with Zend Framework MVC. In order to integrate this code with joomla will need one additional files. In my case the file is Router.php

I have create this file in com_advertiser/Joomla/Controllers/Plugins/ directory.

The code contain in this file is
<?php

require_once('Zend/Controller/Plugin/Abstract.php');
class Joomla_Controllers_Plugins_Router extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$task = $request->getParam('task')
switch($task) {
case 'edit':
$request->setActionName('edit');
break;
case 'save':
$request->setActionName('save');
break;
default:
$request->setActionName('index');
break;
}
}
}

First I’ve include plugin class and then extended my Router class from Zend_Controller_Plugin_Abstract.

This Zend_Controller_Plugin_Abstract class contain a method preDispatch that is called before any controller is called in the routing process.

In the preDispatch method, I get the param “task” and write a switch statement to check this param. If it is edit, I give control to my editAction of the default IndexController. And similarly if it is save, I route request to my saveAction and by default, if no parameter is specified, the request will be dispatched to indexAction of my IndexController.

That’s it.

Now if you write

http://localhost/joomla/administrator/index.php?option=com_advertisers&task=save

It will show what ever you have written in your save.phtml file.

And similarly if you write

http://localhost/joomla/administrator/index.php?option=com_advertisers&task=edit

it will route you to editAction and will display whatever you have define there.

Any question and suggestion are welcomed.

Monday, July 6, 2009

Zend Framework: Zend_Config examples

Zend_Config is used to simply access to, and use of configuration data in Zend Framework application.
Zend_Config currently provide adapters for getting configuration data from xml and ini files. You can also store configuration data in array and pass that array to the Zend_Config constructore, this however is not a recommended way. Configuration data is mostly stored in either xml files or ini files.
In this tutorial I am going to put shad on the usage of Zend_Config and will give you example of how to keep data in array, ini and xml file and then use that using Zend_Config.
So let’s have a look.
To hold configuration data in form of array, you will need to write
$configArray = array(
'database' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => localhost',
'username' => 'user_name',
'password' => 'user_password',
'dbname' => 'database_name'
)
)
);


You can clearly see that we have defined an associative array containing database information.
Now as you have defined an array having configuration information, next step is to create an object of Zend_Config class passing the above array. The code will look like the following
$config = new Zend_Config($configArray);

Now, if you want to make database configuration, simply write
$db= Zend_Db::factory($config->database);

To store the above information in ini file, create config.ini somewhere in your application directory structure, and write the following code in it.
[development]

database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user_name
database.params.password = user_password
database.params.dbname = database_name


After defining ini file, simply write
$config = new Zend_Config_Ini(‘path/to/ini/config.ini’,’ development’);

in your application.

The database configuration is same as we done earlier.
$db = Zend_Config::factory($config->database);

Similarly if you like to use, xml file for you application configuration, create config.xml somewhere in your application directory structure and write
<?xml version="1.0"?>
< development >
<database>
<adapter>pdo_mysql</adapter>
<params>
<host>db.example.com</host>
<username>dbuser</username>
<password>secret</password>
<dbname>dbname</dbname>
</params>
</databse>
</ development >


Now either in your bootstrap file or where you want to initialize configuration, write
$config = new Zend_Config_Xml(‘path/to/xml/config.xml’,’development’);
For database configuration, simply write
$db = Zend_Db::factory($config->database);

That's it. cheers.

Sunday, July 5, 2009

Creating radio button in Zend Framework

Zend Framework Form: working with radio buttons
I have already discussed creation of Zend_From in my previous articles. In this article I'd discuss how to work
with radio buttons in Zend Framework Form.

In your Zend_Form, radio buttons can be created using two methods.
The first one is
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$gender = $this->createElement('radion','gender');
$gender->setLabel('Gender:')
->addMultiOptions(array(
'male' => 'Male',
'female' => 'Female'
))
->setSeparator('');
}
}


In the above code we first create our form by extending it from Zend_Form, override its init() method and setting its method and action attributes.
Next we create our radio button as
$gender = $this->createElement('radion','gender');

Here first argument specify that we want to create radion button element of the form and the second argument set the name
and id of the radio button element group. In the next line we call addMultiOptions() method giving its array of optional
values. and lost but not least, I am calling method setSeparator for placing both radio buttons on the same line. If this
setSeparator method is not called, each radion button will appear on separate line.

The above radio button can also be created as
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$gender = new Zend_Form_Element_Radio('gender');
$gender->setLabel('Gender:')
->addMultiOptions(array(
'male' => 'Male',
'female' => 'Female'
))
->setSeparator('');
}
}


The only difference in the above two example is that I have placed
$gender = $this->createElement('radion','gender'); 

With
$gender = new Zend_Form_Element_Radio('gender');

Both statements give the same result.

For setting different radio button options, you can also use the following method.
$gender->addMultiOption(‘male’,’Male’);
$gender->addMultiOption(‘female’,’Female’);

Ajax with Json and prototype in Zend Framework

I used JSon for the first time in my application today. Zend provide a very easy way to create JSon response.
In this article I would use Prototype to make ajax call. Hopefully you will now a bit about Prototype. Anyway if not, it would not be a hard job to understand it after reading my article.
So let’s get started.
Consider you have the following form.


The scenario is
When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.

For this purpose you would need to have a controller/Action(s), a model and template file.
In your form attach the following attrib to your name element as

<?php
$name = $this->createElement('select','name');
$name->addMultioptions(array(
'select'=>'[select]',
'1' => 'Faheem',
'2' => 'Abbas'
));

$name->setAttrib('onchange','AutoFill()');

In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.

In your controller initialize your form and assign it to the view template as
$form = new MyCustomForm();
$this->view->form = $form;

Now in your view template file write the following.
Write the following javascript code.
<script>
function AutoFill()
{
new Ajax.Request(
"<?=$this->url(array('controller'=>'user','action'=>'getdata'))?>",
{
method:'get',
parameters: {id: value},
onSuccess: FillForm
}
}

function FillForm(rsp)
{
var card = eval('(' + rsp.responseText + ')');
$('address1').value = card.items[0].address1;
$('address2').value = card.items[0].address2;
$('postalcode').value = card.items[0].postalcode;
}
</script>

To get response you will need to create an action and write the following code
<?php
class User extends Zend_Controller_Action
{
public function indexAction()
{
$form = new MyCustomForm();
$this->view->form = $form;
}

public function getdataAction()
{
$this->_helper->layout()->disableLayout();
$users = new Users();

$this->_helper->viewRenderer->setNoRender();
if ($this->getRequest()->isXmlHttpRequest()) {
$id = $this->_getParam('id');
$userData = $ users ->getData($id);
$dojoData= new Zend_Dojo_Data('id',$userData,'id');
echo $dojoData->toJson();
}
}
}

In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.
In the next few lines we check for ajax request, get id, call our getData model method.
We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().

In our model we have code like the following.
<?php
class Users extends Zend_Db_Table
{
protected $_name = 'users';

public function getData($id)
{
$select = $this->_db->select()
->from($this->_name,
array('address1','address2'….))
->where('id = ?', $id);
$result = $this->getAdapter()->fetchAll($select);
return $result;
}
}


That's it. Cheers.

select box in Zend framework: code and example

Though I’ve already discuss how to create dropdown in one of my previous article, however here I would discuss it a bit in detail.

You can create it using the following code.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$country = $this->createElement('select',’countries’);
$country ->setLabel('Countries:')
->addMultiOptions(array(
'US' => 'United States',
'UK' => 'United Kingdom'
));
}
}


Or can also be created using the following code.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$country = new Zend_Form_Element_Select('countries');
$country ->setLabel('Countries:')
->addMultiOptions(array(
'US' => 'United States',
'UK' => 'United Kingdom'
));
}
}


The options are hard code in both of the cases. This will not be requirement always.
Sometime or most of the time application need that drop down should be populated fetching records from the data base. So for this purpose I would like to implement the following code.
Fist in your model write the following.
<?php
class Countries extends Zend_Table
{
protected $_name = 'countries';
public function getCountriesList()
{
$select = $this->_db->select()
->from($this->_name,
array('key' => 'id','value' => 'country_name'))
$result = $this->getAdapter()->fetchAll($select);
return $result;
}
}

Keep in mind that the records we fetch will have an associated array having id as key and country name as value. If you don’t defined the above array, array(‘key’ => ’id’,’value’ => ‘country_name’), as I have defined, you will not get what you want. So be careful while fetching records for constructing drop down.

And now in your form write the following code.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$countries = new Countries();
$countries_list = $countires->getCountriesList();

$country = new Zend_Form_Element_Select('countries');
$country ->setLabel('Countries:')
->addMultiOptions( $countriesList
));
}
}


In the above code the only thing changes is
1. I have instantiated model using
$countries = new Countries();

2. Call getCountiresList() method. And assign the list to the instead of assign hard coded values.

Sending Email with attachment in Zend Framework

You may have used Php for sending emails in your application. I haven’t experienced it in plain php, so I don’t know whether its easy or difficult. I, however, know that Zend Framework provide very easy way for sending emails. You can even attach files with your email with single method call.
In this article I am going to discuss how to send email with attachments. Please do tell me whether it helped you or not.

In your controller, write something like this.
$emial_body = “<table><tr><td>Body of the email</td></tr></table”;

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($email_body);
$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();


This, although, will send email, however it’s not a good approach to create email in your controller as your mail body may contain thousands of words.

The best approach is to create a template, that contain the contents that will act as body of the email. To achieve this, create a file called emailExample.phtml in your /application/views/scripts/templates/ directory. And write the contents you want to put, those contents will serve as body of the email you are going to send.

I am having the following code in my emailExample.phtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<table>
<tr>
<td>
all my contents here.
</td>
</tr>
</table>
</body>
</html>




Now in your controller, write
$myView = new Zend_View();
$myView->addScriptPath(ROOT_DIR . '/application/views/scripts/templates/');
$html_body = $ myView ->render(emailExample.phtml');

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($html_body);

$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();


Here we are first creating an instance of Zend_View, call addScriptPath() to add script path- directory path where our template file reside and which serve as body of our email.
We then get the template by calling render() method on that view object, giving it the name of the template. The rest of the process is same, creating Zend_Mail object, setting body and so on.
Another question come to mind is how
to send an attachment?
This is pretty simple too.
First you will need to get the contents of the file, by calling a method file_get_contents(), like this.
$fileContents = file_get_contents(‘path/to/file’);

And then call a simple method called createAttachment (), as
$file = $mail->createAttachment($fileContents);

And set the name of the attachment as
$file->filename = "yourfile.doc";

That’s it. Cheers.

Saturday, July 4, 2009

Zend Framework building complete application

Well, I have written lots of separate article on Zend Framework. Hopefully most of folk out there searching for valuable help may have gotten some from my articles.
This time my objective is to share everything with you, from basic configuration till to building complete Zend Framework application.
This article will cover
1. How to make initial configuration.
2. How to use Zend_Auth for authentication
3. Using Zend_Session for handling sessions
4. What are models and how to create them
5. Using Zend_Db to handle backend database for storing valuable information.
And much more.
So let’s get started.
1. Creating directory structure and making initial configuration
Zend Framework is based on MVC design patterns. MVC stands for Model, View, Controller. A simple definition of MVC design pattern is to separate business logic from presentation logic.
In order to work with Zend Framework MVC design pattern, you’ll need to make necessary directory structure. There are various ways of making directory structure, I, however will use the most easier to create and understand structure.

The structure I created is.
html_root
/application
/controllers
IndexController.php
/models
Users.php
/forms
LoginForm.php
/views
/scripts
/dojo
index.phtml
/libaray
/Zend
/js
/css
/images
/index.phtm


On the top level we have html_root directory, containing application directory, library, js, css and images. It also contain index.phtml called our bootstrap file. This file contain all our configuration code. Further more application directory contain controller, models forms and views directories. Library directory contains Zend components. Js contain all our js files, css contains css files and images contains all images used in our application.
On the hard drive our directory structure looks like

Keep in mind that controllers directory contain our entire controllers, form directory contain all forms used in our application. Model contains php files contain our business logic. Views/scripts contain template files against each controllers.

Now as we have made necessary directory structure, next step is to make necessary configuration in our bootstrap file.
2. Making necessary configuration in our bootstrap- index.php file.
The most important file, that will get all request and route them to specific controllers. It contain code for setting include path, initializing front controller, set controllers path and call dispatch method.
<?php
define('ROOT_DIR', dirname(__FILE__));

set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/library'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . ROOT_DIR . '/application/forms'
. PATH_SEPARATOR . get_include_path()
);

require_once "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);

$frontController = Zend_Controller_Front::getInstance();

$frontController->throwExceptions(true);

$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
?>


The code is very simple to explain. The first line define path to our root directory.
The next lines set include path to /library, /application/models and /application/forms.

Next lines are very important
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();


Help in loading all php files we need in our application. If we don’t use this code, we will need to include require_once statement to load php files needed.

In next lines we get instance of the front controller, set controllers directory and call dispatch method.
Front controller is responsible for handling the user request. It takes the request and on specific criteria take appropriate action.
That’s it. Its our configuration file. Simple and easy.

3. Creating controllers and views
In html_root/application/controllers, create IndexController.php and put the following code in it.
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
}


Every controller must be extended from Zend_Controller_Action and can contain as many methods as possible. Method defined in controllers is called action. Once you create action in the controller, next step is to create view template. For this purpose, in html_root/application/views/scripts/, create index/index.phtml and put the following code in it.
Hello world


That’s it.
Now if you browse
http://localhost/html_root/

You will see
Hello World
If you don’t see “Hello world” printed, read the above guide lines again.
As we have now successfully created directory structure and bootstrap file, its time to make other necessary configuration for database.

4. Configuration for working with database
How a web application can be completed without usage of database. Different web application uses different database. Some uses Mysql, other SQLite, SQL server and Oracle. One of the nice thing about Zend Framework is that it support multiple database servers.
Here we are going to making configuration for Mysql server.
For database configuration, first create config.ini in html_root/application/ and write the following code in it.
[general]
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.username = root
db.params.password =
db.params.dbname = zend


Now in your bootstrap file make the following changes.
<?php
define('ROOT_DIR', dirname(__FILE__));

set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/library'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . ROOT_DIR . '/application/forms'
. PATH_SEPARATOR . get_include_path()
);

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

$config = new Zend_Config_Ini(ROOT_DIR.'/application/config.ini', 'general');
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);


$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
?>


First we load our config.ini file that contain our database configuration. Next we call static factory method of Zend_Db giving it $config->db for database configuration and at the end we set default adapter for our database tables.
That’s it. We have now done all necessary configurations.
Next step is to store and retrieve data from database
5. Working with database data
Now we are going to make an application that will save, display and edit data in the database.
First execute the following query.
CREATE TABLE `users` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`firstName` VARCHAR( 50 ) NOT NULL ,
`lastName` VARCHAR( 50 ) NOT NULL ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL
)


This query create a table called users in the database.
Next step is to create model against this table. In your html_root/application/models/ create Users.php and write the following code in it.
<?php
class Users extends Zend_Db_Table
{
protected $_name = "users";
}


The only thing we have done is extend our Zend_Db_Table and define name of the model. This name must be same as the database table name.
Now in your html_root/application/controllers/IndexController.php, write
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data;
}
}


After making changes in IndexController.php, next step is to make changes in html_root/application/views/scripts/index/index.phtml. write the following code in it.
<h4>List of users</h4>
<h5><a href="add" style="color:blue">Add new user</a></h5>
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tboody>
<?php foreach ($this->data as $d) {?>
<tr>
<td><?=$d['firstName']?></td>
<td><?=$d['lastName']?></td>
<td><?=$d['username']?></td>
<td><?=$d['email']?></td>
<td><a href="edit/id/<?=$d['id']?>" style="color:blue">Edit</a></td>
</tr>
<?php }?>
</tbody>
</table>


This will show the list of users.
Next we are going to create a form for adding data to users table.
In your html_root/application/forms/ create CustomForm.php and write the following code in it.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
//$this->setAction('add');

$id = $this->createElement('hidden','id');
$firstname = $this->createElement('text','firstname');
$firstname->setLabel('First Name:')
->setAttrib('size',50);
$lastname = $this->createElement('text','lastname');
$lastname->setLabel('Last Name:')
->setAttrib('size',50);
$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',50);
$email = $this->createElement('text','email');
$email->setLabel('Email:')
->setAttrib('size',50);
$password = $this->createElement('password','password');
$password->setLabel('Password:')
->setAttrib('size',50);

$password2 = $this->createElement('password','password2');
$password2->setLabel('Confirm Password::')
->setAttrib('size',50);
$register = $this->createElement('submit','register');
$register->setLabel("Register")
->setIgnore(true);

$this->addElements(array(
$firstname,
$lastname,
$username,
$email,
$password,
$password2,
$id,
$register
));
}
}


We have successfully created our form, next we are going to write necessary code in our IndexController.php
Write the following code in it
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
}

public function addAction()
{
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;


if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->insert($formData);
}
}
}
}


The code in addAction create form, get posted data, check whether password and confirm password match and then insert data in the users table.

Now create add.phtml in html_root/application/views/scripts/index/ and write the following code in it.
<h3>Add User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>


Next we are going to create action for editing the users table data. Write the following code in the your IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
//$this->_helper->layout->disableLayout();
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
}

public function addAction()
{
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;


if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->insert($formData);
}
}
}

public function editAction()
{
$users = new Users();
$form = new CustomForm();

$id = $this->_getParam("id",1);
$select = $users->select()
->where("id = ?",$id);
$data = $users->fetchRow($select);
$form->populate($data->toArray());


if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->update($formData,"id = $id");
}
}
$this->view->form = $form;
}

}


The above code fetch the data and populate the form, and then get the posted data and update the users table based on the id.

Create edit.phtml in html_root/application/views/scripts/index/ and write the following code in it.
<h3>Edit User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>


6. Create authentication application
As now we have created database application successfully, we are going to create authentication application.

(i). Creating login form
in your html_root/application/forms/ create LoginForm.php and write the following code in it.
<?php
class LoginForm extends Zend_Form
{
public function init()
{
$this->setName('login');
$this->setMethod('post');

$userName = $this->createElement('text', 'userName',array('label' => 'username' ));
$userName->addFilters(array('StringTrim'))
->addValidator('StringLength', false,array(5,50))
->setValue('')
->setRequired(true);

$password = $this->createElement('password','password',array('label' => 'password' ));
$password ->setRequired(true)
->addValidator('StringLength', false,array(5,50))
->setValue('');

$submit = $this->createElement('submit','save',array('label' => 'login'));
$submit->setRequired(false)
->setIgnore(true);

$this->addElements(array(
$userName,
$password,
$submit,
));
}
}


In the above form we add two elements, a text box for entering username and password field for entering user password. We also add submit input box.
(ii).Next we create AuthController.php in html_root/application/controllers/ and write the following code
<?php
class AuthController extends Zend_Controller_Action
{
public function loginAction()
{
$form = new LoginForm();
if ($this->getRequest()->isPost()) {
$values = $this->_request->getPost();
if ($form->isValid($values)) {
$users = new Users();
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter());
$authAdapter->setTableName('users');
$authAdapter->setIdentityColumn('userName');
$authAdapter->setCredentialColumn('password');

$authAdapter->setIdentity($values['userName']);
$authAdapter->setCredential($values['password']);
try {
$result = $auth->authenticate($authAdapter);
} catch (Zend_Exception $e) {
$this->view->errorMsg = $e->getMessage() . "<br>";
}

if ($result->isValid()) {
$data = $authAdapter->getResultRowObject();
$sess = new Zend_Session_Namespace();
$sess->username = $data->useruame;
echo "Welcome <b>".$data->username.'</b><br>You successfully logged in.';
} else {
echo "invalid username or password try again.";
}
}
}
$this->view->form = $form;
}
}


In login action we initialize our login form, check for submitted data. We then instantiate our user model as well as Zend_Auth. Setting table name, identity column and credential column. We then pass values submitted through form to identity column and credential column. After setting these things we call authenticate() method.
This authenticate column perform authentication for us.
We then call isValid() method that return true or false based on the authentication.
If isValid() return true, we get the user specific information by calling getResultRowObject() method.
We then create session and assign username to it.
The last thing we will need to create is view template against login action. In html_root/application/views/scripts create auth/login.phtml and write the following code in it.
<fieldset style="width:400px">
<legend>Login</legend>
<?php
echo $this->form;
?>
<div><a href="../index/add" style="color:blue">New user Sign up here</a></div>
</fieldset>


That’s it. Our login authentication. For registration, you can use add form I have previously created.
I think its enough for now. I will discuss other things later on hopefully.