jump to navigation

Zend Framework : Basic Database operations with the Table Data Gateway Patern May 1, 2011

Posted by Tournas Dimitrios in Zend Framework v1.10.
trackback

First of all ,the material of  this article is derived from Rob Alen’s tutorial – So all applause goes to him . Although his book is out-dated , it can be used as a starting point for learning the Zend Framework ( no I’m not promoting this book 🙂 ) . My previous article made an introduction to the basic concepts related to the Table Data Gateway Pattern , so I’ll skip the basics . This article will take a more practical approach to demonstrate how the TDG-pattern can be used to handle basic database operations . The final result will be a web – Interface to handle users on a Database ( crud operations ) . Just download the source code of this article and use it as a reference ( the zip file also contains the sql-schema of the database ) . Readers that follow my articles should already be familiar with the skeleton (layout) of this demo-project , as it has been used across many articles .

I presume that you already have finished my previous article , so your project is up to the point where :

  • Database credentials are configured in the application.ini file
  • The Models directory contains a Model Class that implements the TDG-pattern .
  • Optionally a layout is configured ( my layout is CSS based ) .

Proceed with the following steps :

  • Instantiate a new Controller (ManageUsersController )
  • Add functionality to the TDG-Calss
  • Configuring  ManageUsers/index.phtml file ( Users Interface panel )
  • Creating a Form to interact with the database
  • Creating  Actions inside the ManageUsersController

Instantiate a new Controller (ManageUsersController ) :
zf create controller ManageUsers

Add functionality (business logic ) to our Table Data Gateway Class :

class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{

    protected $_name = 'users';

	public function getUsers($id)
	{
	$id = (int)$id ;
	$row = $this->fetchrow('id = '. $id );
	if (!$row) {
	throw new Exeption("Sorry could not find row $row");
	}
	return $row->toArray();
	}

	public function addUser($firstname , $lastname , $email)
	{
	$data = array(
		'Firstname' => $firstname ,
		'Lastname'  => $lastname  ,
		'emai '     => $email ,
		);
		$this->insert($data);
	}
	public function updateUser($id ,$firstname , $lastname , $email)
	{
	$data = array(
		'Firstname' => $firstname ,
		'Lastname'  => $lastname ,
		'email'		=> $email ,
		);
		$this->update($data , 'id= ' . (int)$id);
	}
	public function deleteUser($id)
	{
		$this->delete('id =' . (int)$id);
	}

}

The code is self – explanatory , I hope . Whilst not needed from this article , you can also ” tell ” Zend_Db_Table about related tables and it can fetch related data to .

Configuring  ManageUsers/index.phtml file ( Users Interface panel )  :

<h1><center> Manage all Users </center></h1><hr>
<p><a href="<?php echo $this->url(array('controller' => 'ManageUsers',
	'action' => 'add')); ?>"><h2>Add new User </h2></a></p>
<p><a href="<?php echo $this->url(array('controller' => 'index',
	'action' => 'index')); ?>"><h2>Return to Home Page </h2></a></p>
<table border="2" width="100%"> 
	<tr>
		<th>FirstName</th>
		<th>LastName</th>
		<th>Email</th>
		<th>&nbsp;</th>
	</tr>
	<?php foreach($this->users as $users): ?>
	<tr>
	<td><?php echo $this->escape($users->Firstname);?></td>
	<td><?php echo $this->escape($users->Lastname);?></td>
	<td><?php echo $this->escape($users->email);?></td>
	<td>
	<a href="<?php echo $this->url(array('controller' => 'ManageUsers',
			'action' => 'edit' , 'id'=>$users->id));?>">Edit</a>
	<a href="<?php echo $this->url(array('controller' => 'ManageUsers',
			'action' => 'delete' , 'id'=>$users->id));?>">Delete</a>
				
	</td>
	</tr>
<?php endforeach ; ?>

</table>

Again the code is self-explanatory . We take the array object that was created from the controller , iterate with a foreach loop ” and display the results inside a table . A note for newcomers : the script use a url view helper ” to produce all hyperlink automatically for us .

Creating a Form to interact with the database :

My previous article outlined the basic concepts for the Form component . This article will take a different approach to implement a Form component , we will create a Form Class . The Zend tool “zf” makes the procces simple , just run : zf  create form Users
This will create a directory Forms and the Application_Form_Users Class ( extend the Zend_Form Class ) .  The basic concepts are outlined in my previous article , so I’ll skip to the next section .

Creating  Actions inside the ManageUsersController :
Let’s create the Controller actions to interact with the database :
zf  create action add ManageUsers
zf  create  action  edit  ManageUsers
zf  create  action  delete  ManageUsers
Actually these Controller-Action functions host the control logic to validate , filter and enable the CRUD operations that are provided from the Table Data Gateway Class .

The final code for the ManageUsers Controller is :

<?php

class ManageUsersController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
     $users = new Application_Model_DbTable_Users();
	 $this->view->users = $users->fetchAll();
    }

    public function addAction()
    {
        $form = new Application_Form_Users();
		$form->submit->setLabel('Add');
		$this->view->form = $form ;
		if ($this->getRequest()->isPost()) {
		$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)) {
				$firstname = $form->getValue('firstname');
				$lastname  = $form->getValue('lastname');
				$email		= $form->getValue('email');
				$users = new Application_Model_DbTable_Users();
				$users->addUser($firstname ,$lastname , $email );			
				$this->_helper->redirector('index');
				}else {
				$form->populate($formData);
				}
				}
				
    }

    public function editAction()
    {
        $form = new Application_Form_Users();
		$form->submit->setLabel('Save');
		$this->view->form = $form;
		if ($this->getRequest()->isPost()) {
		$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)) {
				$id = (int)$form->getValue('id');
				$firstname = $form->getValue('firstname');
				$lastname  = $form->getValue('lastname');
				$email		= $form->getValue('email');
				$users = new Application_Model_DbTable_Users();
				$users->updateUser($id ,$firstname ,$lastname , $email );			
				$this->_helper->redirector('index');
				}else {
				$form->populate($formData);
				}
				}else{
				$id = $this->_getParam('id', 0);
					if ($id > 0) {
					$users = new Application_Model_DbTable_Users();
					$form->populate($users->getUsers($id));
					}
					}
    }

    public function deleteAction()
    {
        if ($this->getRequest()->isPost()) {
		$del = $this->getRequest()->getPost('del');
			if ($del == 'Yes') {
				$id = $this->getRequest()->getPost('id');
				$users = new Application_Model_DbTable_Users();
				$users->deleteUser($id);
				}
				$this->_helper->redirector('index');
				}else {
				$id = $this->_getParam('id' , 0);
				$users = new Application_Model_DbTable_Users();
				$this->view->user = $users->getUsers($id);
				}
    }

}

The picture below shows the final result of this article .

Download the source code and experiment .

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s