Zend Framework-First Database driven application

Zend Framework is an open source, object-oriented web application framework implemented in PHP 5 designed to eliminate the tedious details of coding and let you focus on the big picture. One of its strengths is the highly modular Model-View-Controller (MVC) design, making your code more reusable and easier to maintain.

The requirements as under :

  • Latest version of PHP, MySql Database and Apache Web Server(httpd) are installed on your system.
  •  mod_rewrite extension of Apache must be enabled. To enable, do the following (only for Debian based distros, like Ubuntu) :
sudo a2enmod rewrite
  •   Don’t forget to restart Apache.
sudo service apache2 restart
  • Make a directory structure like this, project/ must be placed inside the /var/www/ Directory :
    project/
    ——-application/
    ——————controllers/
    ——————forms/
    ——————models/
    ——————views/
    ————————-scripts/
    ———————————-error/
    ———————————-index/
  • Directory “project/” is main working directory of the our application.
  • Download Zend Framework minimal package from http://framework.zend.com/download/latest. Then Extract the Library folder inside the archive to our project/ directory, graphically or use following commands.
  • Now Log in to root. Run the following commands:

sudo -s

cd  /home/username/Downloads/

cd  zend-minimal

cp  library /var/www/project

  • Directory name: Zend-minimal.tar.gz can vary according to the version of Zend, you downloaded.
  • Create index.php file inside the project/ directory and write the following code:
<?php
 define(‘ROOT_DIR’, dirname(__FILE__));
//including the MVC (Model-View-Controller) directories and Zend library
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()
 );
//Autoloading the zend
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();
 ?>
  • When we will open this file, Zend will lookout for IndexController.php inside the controllers/ directory which we have defined in the index.php file, therefore create the IndexController.php inside project/application/controllers/ and write the following code in it:
// setting up the controller here..
 <?php
class IndexController extends Zend_Controller_Action
 {
 public function indexAction()
 {
 }}
?>
  • Now the inside the IndexController.php we created the class with the same name, and indexAction() is created. indexAction() will look for index.phtml inside the project/application/views/scripts/index/ so just create it, whatever you will write in this file, directly comes to your view. Similarly create error.phtml in project/application/views/scripts/error/ and write anything that will identify you, whenever you faced the error.
  • Create .htacess file in project/ folder and write following code in it
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
  • This is the file where mod_rewrite extension of Apache Web Server(httpd) is used to rewrite the URLs, as I will not discuss this now.
  • Create a Database and note down the name you created. Create table by executing the following query :

    CREATE TABLE users (id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(75),pname varchar(75),address varchar(100),
    contact varchar(15),hobbies text,PRIMARY KEY (id));
  • Now configure the database settings. Create a file config.ini inside the /project/application/ directory, write the following code, fill in your details and save the file.
[general]
db.adapter = "PDO_MYSQL"
db.params.host = "localhost"
db.params.username = "root"
db.params.password = ""
db.params.dbname = "project"
  • We have created the Database configuration file, now add the following lines to index.php
$config = new Zend_Config_Ini(ROOT_DIR.'/application/config.ini', 'general');
 $db = Zend_Db::factory($config->db);
 Zend_Db_Table::setDefaultAdapter($db);
  • It should look like :
<?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);
//database configs initialized
$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();
 ?>
  • Also added a form to view the data in specific defined order as desired by the viewer, So create a file named SortForm.php inside /project/application/forms directory and write following code:
<?php
 class SortForm extends Zend_Form
 {
 public function init()
 {
$this->setMethod('post');
 $this->addElement('radio', 'sortby', array(
 'label' => 'Sort by Column:',
 'multioptions' => array(
 'name' => 'Name',
 'pname' => 'Parent\'s Name',
 'address' => 'Address',
 'contact' => 'Contact',
 'hobbies' => 'hobbies'
 ),));
$this->addElement(‘radio’, ‘sorttype’, array(
 'label' => 'Sort Type:',
 'multioptions' => array(
 'ASC' => 'Aescending',
 'DESC' => 'Descending'
 ),));
 $this->addElement('text','search',array(
 'label'=>'search name'));
 $this->addElement('submit','sortdata',array(
 'label'=>'Sort Data'));
}
 }
 ?>
  • Update IndexController.php
<?php
 class IndexController extends Zend_Controller_Action
 {
 public function indexAction()
 {
//loading Users model, ans SortForm
 $users = new Users();
 $form = new SortForm();
 $this->view->form = $form;
//searching and sorting logic
 if ($this->getRequest()->isPost()) {
 $sortData = $this->_request->getPost();
}
 if((empty($sortData['search'])==0)){
if(isset($sortData['sortby']) && isset($sortData['sorttype']))
 {
$data=$users->fetchAll($users->select()->order($sortData['sortby']." ".$sortData['sorttype'])->where('name = ?', $sortData['search']));
 }
 else
 {
$data=$users->fetchAll($users->select()->where('name = ?', $sortData['search']));
 }}
elseif(isset($sortData['sortby']) && isset($sortData['sorttype'])){
$data=$users->fetchAll($users->select()->order($sortData['sortby']." ".$sortData['sorttype']));
 }
else {
$data = $users->fetchAll($users->select());
}
$this->view->data = $data;
 }
}
?>
  • Also update index.phtml
<h3>All Added Entries</h4>
<?php
echo $this->form;
 ?>
<table border="1">
<tr>
 <th>Name</th>
 <th>Father's Name</th>
 <th>Address</th>
 <th>Contact</th>
 <th>Hobbies</th>
 </tr>
<?php foreach ($this->data as $d) {?>
 <tr>
 <td><?php echo $d['name'];?></td>
 <td><?php echo $d['pname'];?></td>
 <td><?php echo $d['address'];?></td>
 <td><?php echo $d['contact'];?></td>
 <td><?php echo $d['hobbies'];?></td>
 </tr>
 <?php }?>
</table>
  • We have to setup a model for the Database table which we are using, which is also used in indexAction() of IndexController.php file so, create a file Users.php which resides in /project/application/models/ directory and write the corresponding code.
<?php 
class Users extends Zend_Db_Table 
{    protected $_name = "users"; }
 ?>
  • Create ErrorController.php inside project/application/controllers/ and write the code, which we are using to display errors if any occurs.
<?php
class ErrorController extends Zend_Controller_Action {
public function errorAction() {
 $errors = $this->_getParam('error_handler');
 $exception = $errors->exception;
echo $exception->getMessage();
 echo "<br /><pre>";
 echo $exception->getTraceAsString();
 }
 }
 ?>
  • Next is the Data Entry form for user, create a form named CustomForm.php inside project/application/forms/ directory and write the following code to create a form for Data Entry.
<?php
 class CustomForm extends Zend_Form
 {
 public function init()
 {
 $this->setMethod('post');
$id = $this->createElement('hidden','id');
 $name = $this->createElement('text','name');
 $name->setLabel('Name:')
 ->setAttrib('maxlength',75);
 $pname = $this->createElement('text','pname');
 $pname->setLabel('Father's Name')
 ->setAttrib('maxlength',75);
 $address = $this->createElement('text','address');
 $address->setLabel('Address:')
 ->setAttrib('maxlength',100)
 ->setAttrib('size',75);
 $contact = $this->createElement('text','contact');
 $contact->setLabel('Contact:')
 ->setAttrib('maxlength',15)
 ->setAttrib('size',15);
$hobbies = $this->createElement('textarea','hobbies');
 $hobbies->setLabel('Hobbies (seprate with coma(,)):')
 ->setAttrib('size',255)
 ->setAttrib('rows',10)
 ->setAttrib('cols',40);
 $addentry = $this->createElement('submit','addentry');
 $addentry->setLabel("Add Entry")
 ->setIgnore(true);
$this->addElements(array(
 $name,
 $pname,
 $address,
 $contact,
 $hobbies,
 $id,
 $addentry
 ));
 }
 }
 ?>
  • Updates version of IndexController.php is following, please make corresponding changes:
<?php
 class IndexController extends Zend_Controller_Action
 {
 public function indexAction()
 {
 $users = new Users();
 $form = new SortForm();
 $this->view->form = $form;
 if ($this->getRequest()->isPost()) {
 $sortData = $this->_request->getPost();
}
 if((empty($sortData['search'])==0)){
if(isset($sortData['sortby']) && isset($sortData['sorttype']))
 {
$data=$users->fetchAll($users->select()->order($sortData['sortby']." ".$sortData['sorttype'])->where('name = ?', $sortData['search']));
 }
 else
 {
$data=$users->fetchAll($users->select()->where('name = ?', $sortData['search']));
 }
}
elseif(isset($sortData['sortby']) && isset($sortData['sorttype'])){
$data=$users->fetchAll($users->select()->order($sortData['sortby']." ".$sortData['sorttype']));
 }
else {
$data = $users->fetchAll($users->select());
}
$this->view->data = $data;
 }
//add action
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)) {
 unset($formData['addentry']);
 $users->insert($formData);
 echo "Data Successfully stored";
 }
 }
 }
}
 ?>
  • Create add.phtml file in project/application/views/scripts/index/ and write the following code in it.
<h3>Add User</h3>
 <?php
 if ($this->errorMsg) {
 echo $this->errorMsg;
 }
 ?>
 <?php echo $this->form;
 ?>
This entry was posted in Zend Framework. Bookmark the permalink.

3 Responses to Zend Framework-First Database driven application

  1. sgb says:

    simple gud one

  2. sgb says:

    hello
    Fatal error: Interface function Zend_View_Interface::baseUrl() cannot contain body in D:\ZendFramework-1.11.11\ZendFramework-1.11.11\library\Zend\View\Interface.php on line 36

    • Parveen Kaur says:

      I am not getting the point where you get this error. Please explain at which step you get this error. Is index page is displaying?

      Thank you for your interest.
      Good Luck.

Leave a comment