Abstract database models with PDO MySQL (Zend Framework)

Zend Framework allows you to create models which extend Zend_Db_Table_Abstract. The snippets below demonstrate abstract database models.

Modify application.ini for your database connection.

resources.db.adapter = PDO_MYSQL
resources.db.params.host = localhost
resources.db.params.username = databaseuser
resources.db.params.password = databasepass
resources.db.params.dbname = databasename

Example model

<?php

class Application_Model_Example extends Zend_Db_Table_Abstract
{

    protected $_name = 'example'; // Use the example table

    public function fetchAllExamples(){
	// Will return all rows in the example table
	return $this->fetchAll();
    }

    public function getExample($exampleId){
	// Will return an example row with a given id
	$exampleSelect = $this->select()->where('exampleId= ?', $exampleId);
	return $this->_fetch($exampleSelect);
    }

}

?>

The framework will automatically initiate the database connection and will allow you to use the Application_Model_Example class to perform database operations on the example table.

This entry was posted in PHP and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted August 1, 2011 at 1:56 pm | Permalink

    Thanks very much for this example, I’ve finally got my head around how models work using this great example. I’ve been trying to create a User model inside the my User module:

    Only problem i came across was using a model inside a module i didn’t need the Application_ bit in the class names, so i had User_Model_User.

    To get the model to load i had to make a Bootstrap.php inside the User Module folder :

    Also i linked the controller to the model like so :
    $user = new User_Model_User();
    $this->view->user = $user->getUser($usersessionid);

    Also to display the information in a view i used:

    user as $key => $user) : ?>

    Thanks again, and i hope the above comments are helpful to someone :)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?