Pages

Deploying Your First PHP Application with the Windows Azure Command Line Tools for PHP

Deploying PHP

Creating a Windows GUI Application with PHP



This is a guest blog post by Tim. Tim is a PHP programmer who is interested in Web Design, CSS, and Pizza. He runs the site php.uni.cc where he posts tutorials to help you with PHP, Design, and more. You can also find him over at forums.tizag.com.
Update: This was originally posted towards the end of July 2007. I'm reposting this as I believe it didn't get the attention it deserved. -Jake
This tutorial will show you how to make a basic “Hello World” application using PHP, Winbinder, and the Bambalam Compiler.
First we need to setup our environment. Once you have downloaded Winbinder and Bambalam Compiler from the links above, you should copy the following files into a new folder with the following structure:
  • project_folder/bam.exe #Bambamlam Compiler - rename the old .exe to bam.exe
  • project_folder/helloworld.php #Our “Hello World” source
  • project_folder/winbinder.php #Winbinder - from WinBinder-0.46.0/phpcode/include/
  • project_folder/wb_resources.inc.php #Winbinder - from WinBinder-0.46.0/phpcode/include/
  • project_folder/wb_generic.inc.php #Winbinder - from WinBinder-0.46.0/phpcode/include/
  • project_folder/wb_windows.inc.php #Winbinder - from WinBinder-0.46.0/phpcode/include/
  • project_folder/php_winbinder.dll #Winbinder - from WinBinder-0.46.0/binaries/php4/ext/
  • project_folder/project.bcp #Our Bam. project file
  • project_folder/build.bat #Command to build our project
Once you have the files in order, copy and paste the following lines into the corresponding files.
build.bat

bam project.bcp

pause
On running the file, it will build a .exe based on the parameters in project.bcp and will pause the output so we can see if there are any errors.
project.bcp

OUTFILE helloworld.exe

EMBED helloworld.php

EMBED wb_generic.inc.php

EMBED wb_resources.inc.php

EMBED wb_windows.inc.php

EMBED winbinder.php

MAINFILE helloworld.php

EXTENSION php_winbinder.dll
WINDOWED
This simply tells bam.exe to:
  • Output the .exe to helloworld.exe
  • Embed all the .php files
  • Set helloworld.php as the main file
  • Include the Winbinder extension
  • Not to show the command line
Now that our environment is setup, we can move onto the coding.
First, Open up helloworld.php with you favorite PHP editor.
As you would start off any PHP script, type in:
<?php
Now we need to include winbinder.php. This holds several functions that we need.
<?php

include(”winbinder.php”);
Next, we need to create the application window. We also need to set it in a function.
<?php
include(”winbinder.php”);

$window = wb_create_window(NULL, AppWindow, “Hello World”, WBC_CENTER, WBC_CENTER, 400, 300);
The function wb_create_window has several required parameters. I will explain them now.
  • NULL = The parent window. Since we have no other window, this needs to be NULL.
  • AppWindow = This is the window type. You can find more types in the WinBinder documentation.
  • “Hello World” = The window title.
  • WBC_CENTER = The X starting location. WBC_CENTER is a predefined constant
  • WBC_CENTER = The Y starting location. WBC_CENTER is a predefined constant
  • 400 = The window width
  • 300 = The window height
We will now make the text “Hello World” appear in the window.
<?php

include(”winbinder.php”);

$window = wb_create_window(NULL, AppWindow, “Hello World”, WBC_CENTER, WBC_CENTER, 400, 300);

$hello_world = wb_create_control($window, Label, “Hello World”, 5, 5, 100, 50);
The function wb_create_control has several required parameters. I will explain them now.
  • $window = The objective window. Put the variable of the window you wish to add the control to in that spot.
  • Label = The control type. You can find more control types in the WinBinder documentation.
  • “Hello World” = The default value
  • 5 = The X starting location.
  • 100 = The control width
  • 50 = The control height
Almost done! Finally, we must add the following function that loops the window to keep it alive.
<?php

include(”winbinder.php”);

$window = wb_create_window(NULL, AppWindow, “Hello World”, WBC_CENTER, WBC_CENTER, 400, 300);

$hello_world = wb_create_control($window, Label, “Hello World”, 5, 5, 100, 50);

wb_main_loop();
And there you have it! Now, compile the application by running build.bat. It all went well, it should output helloworld.exe which you should see the window with “Hello World”.
If you wish to expand you’re application making skills, you should read the Bambalam Compile project page and also the WinBinder documentation.


Creating JQuery form in Zend Framework


While few months back, I wrote an article on how to make Dojo Form in Zend Framework. Although dojo has numerous features, however most of the developers around prefer JQuery and prototype.
When Zend provide JQuery extension I wrote and article on how to use JQuery date picker.
While most of guys visited that article demand writing an article on how to create JQuery form in Zend Framework.
So I’m here to show you how to use JQuery extension provide with latest version of Zend Framework for creating wonderful JQuery form.
You will need to follow the steps bellow to create JQuery form.
1. Placing ZendX directory in right place
2. Make necessary configuration in bootstrap file
3. Write necessary code in your layout.phtml file.
4. Create JQuery form
5. and show that form in the template.

Placing ZendX directory in right place:
When you download latest version of Zend Framework and extract the zip file. You will see a directory called “extras”. When open that directory you will find ZendX folder. Copy this to your
Library/ folder at the same level of your Zend directory
You directory structure will be like this.
Library/
Zend/
ZendX/

Making necessary configuration in bootstrap:
After placing the directory you will need to add a bit of code in your bootstrap file.
Add the following lines to your bootstrap file.
$view = new Zend_View();
$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

In the code above, we instantiate our Zend_View object, set helper path, add view to the viewRenderer and finally add viewRenderer the helper broker.
Keep in mind that if you have already instantiate Zend view in your bootstrap, you don’t need to instantiate it twice.
Write necessary code in your layout.phtml file:
The only line you will need to include in your layout file is
echo $this->jQuery();

If you don’t use two step view, you can include this line at the top of each of your view template file instead.
Create JQuery form:
Now you have done all the necessary configuration, its time to create the actual form.
Create JQuery form in Zend framework is piece of cake.
If you want to create form in your controller, write the following code.
$form = new ZendX_JQuery_Form();
$date1 = new ZendX_JQuery_Form_Element_DatePicker(
'date1',
array('label' => 'Date:')
);
$form->addElement($date1);
$elem = new ZendX_JQuery_Form_Element_Spinner(
"spinner1",
array('label' => 'Spinner:')
);
$elem->setJQueryParams(array(
'min' => 0,
'max' => 1000,
'start' => 100)
);
$form->addElement($elem);
$this->view->form = $form;

In the code above we have created our JQuery form object, and add two element date and spinner to it. And then assigned the form to the view template file. Although you can create the form in your controller, however I will strongly discourage it. I will prefer using separate php file and add following code to that file.
class JQueryForm extends ZendX_JQuery_Form
{
public function init()
{
$this->setMethod('post');
$this->setName('frm');
$this->setAction('path/to/action');

$date1 = new ZendX_JQuery_Form_Element_DatePicker(
'date1',
array('label' => 'Date:')
);

$this->addElement($date1);

$elem = new ZendX_JQuery_Form_Element_Spinner(
"spinner1",
array('label' => 'Spinner:')
);

$elem->setJQueryParams(array('min' => 0, 'max' => 1000, 'start' => 100));
$this->addElement($elem);
}
}

We have extended our form from ZendX_JQuery_Form, set its method, name and action and add two elements date and spinner.
Now in your controller/action
    $form = new JQueryForm();

$this->view->form = $form;

Showing form in the template:
In your view template file add only the following line.
    <?php

echo $this->form;

?>

Zend Pagination example


Paginator component is available with Zend Framework v1.6. This component wasn’t available in v1.5. I appreciate Zend for provide such a nice component for pagination. This component, like other component, is so loosely coupled that you can use it wherever you want without worrying about any other component at all.
If you have already created pages and you want to apply pagination to them, it would not be a big deal.
Pagination is three step process.

1. you will need to create template file. In template file you can specify layout of your pagination. i.e. how your first, previous, next and last etc will be displayed.

2. instantiate your pagination class in the controller and pass data source- data source can be an array, values fetched form the database etc.

3. make some change in your template file, where you are showing your records.
Lets have a simple example.
First create a template file pagination.phtml in your “/application/view/script/” folder and place the following code
<div class="pagination" style="width:100%">
<div style="float:left;width:28%">
</div>
<div style="float:right;width:70%;">
<!-- First page link -->
<?php if (isset($this->previous)): ?>
<a href="<?= $this->url(array('page' => $this->first)); ?>">Start</a> |
<?php else: ?>
<span class="disabled">Start</span> |
<?php endif; ?>

<!-- Previous page link -->

<?php if (isset($this->previous)): ?>
<a href="<?= $this->url(array('page' => $this->previous)); ?>">&lt; Previous</a> |
<?php else: ?>
<span class="disabled">&lt; Previous</span> |
<?php endif; ?>
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?= $this->url(array('page' => $page)); ?>"><?= $page; ?></a>
<?php else: ?>
<?= $page; ?>
<?php endif; ?>
<?php endforeach; ?>
<!-- Next page link -->
<?php if (isset($this->next)): ?>
| <a href="<?= $this->url(array('page' => $this->next)); ?>">Next &gt;</a> |
<?php else: ?>
| <span class="disabled">Next &gt;</span> |
<?php endif; ?>
<!-- Last page link -->
<?php if (isset($this->next)): ?>
<a href="<?= $this->url(array('page' => $this->last)); ?>">End</a>
<?php else: ?>
<span class="disabled">End</span>
<?php endif; ?>
&nbsp; Page <?= $this->current; ?> of <?= $this->last; ?>
</div>
</div>

The code above is self explanatory. We are creating links for the pagination.

Next add the following code in your controller.
$sql = 'SELECT * FROM table_name ';
$result = $db->fetchAll($sql);
$page=$this->_getParam('page',1);
$paginator = Zend_Paginator::factory($result);
$paginator->setItemCountPerPage(10));
$paginator->setCurrentPageNumber($page);

$this->view->paginator=$paginator;

In the code above we first fetch records from our database. Then instantiate our paginator by writing
$paginator = Zend_Paginator::factory($result);

And pass it results we have fatched.
We then set number of items per page and current page. On our first visit $page will have value 1.
At the end we assign this paginator to our view template.
And now in view template add the following code
foreach($this->paginator as $record)
{
echo $record['firstname'].'\n';
echo $record['lastname']. '\n'
...
...
}

<?= $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?

We are applying foreach loop to our paginator and echo our records. I assume that you have fistname, lastname columns in your table where you are fetching records form.Last line is compulsory. you need to call the paginator contorller and give it the $paginator, style of the pagination and the file name of the pagination template.

Zend Framework sign up and authentication


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.

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.

Zend Framework SQL Joins Examples


You may have custom of using advanced queries. It often requires writing complex queries if you are working on enterprise, large scale web application(s).
The use of joins can never be ignored.
Zend Framework developers have done tremendous job by providing simple method for implementing joins.
Lets look some examples of different type of joins.
Before discussing joins lets consider we have two tables, “authors” and “books”.
These are associated with author_id.

1. Inner Join
The simplest query will be
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinInner('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->order('column name ASC/DESC');

2. Left Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinLeft('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

3. Right Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinRight('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

4. Full Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

5. Cross Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

Once you write these queries, you can fetch a single row or multiple rows as

$result = $this->getAdapter()->fetchRow($select);
$result = $this->getAdapter()->fetchAll($select);

The first statement fetch only one row, while the second statement fetch the entire dataset.

Zend Framework Buliding 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.