framework.zend.com “Create a Model and Database Table” tutorial fixed, full working code, adapted for MySQL

http://framework.zend.com/manual/1.10/en/learning.quickstart.create-model.html

Well, I agonized over getting this, and if you read the comments on the tutorial, many others have as well, working on my home Snow Leopard as well as on my work XP pc, and I spent countless hours looking for a post just such as this one is now, to no avail, so here it all is, hope it helps somebody:

hosts

In the event that you don’t have this done already, here is what should go in your environment’s hosts file…

Mac: /private/etc/hosts

PC:  C:\WINDOWS\system32\drivers\etc

# Setup “components” Virtual Host
<VirtualHost *:80>
ServerName project
DocumentRoot “C:\xampp\htdocs\project\public// or /Library/WebServer/Documents/project/public

<Directory “C:\xampp\htdocs\project\public” // or /Library/WebServer/Documents/project/public>
Options Indexes FollowSymLinks Includes
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

create the database that this will use

CREATE TABLE IF NOT EXISTS `guestbook` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(32) DEFAULT NULL,
`comment` text,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

add dummy data to the database

INSERT INTO `guestbook` (`id`, `email`, `comment`, `created`) VALUES
(1, ‘ralph@schindler.com’, ‘hello’, ‘2010-09-17 00:00:00’),
(2, ‘foo@bar.com’, ‘goodbye’, ‘2010-09-17 00:00:00’);

if you haven’t done so already, create the user this app will use to connect, and give the user the priviledges they’ll need

CREATE USER ‘guestbook’@’localhost’ IDENTIFIED BY ‘guestbook’;

GRANT ALL ON ‘guestbook’ TO ‘guestbook’@’localhost’;

project/application/Bootstrap.php

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initAutoloader()
{
// Create an resource autoloader component
$autoloader = new Zend_Loader_Autoloader_Resource(array(
‘basePath’    => APPLICATION_PATH,
‘namespace’ => ‘Application’
));

// Add some resource types
$autoloader->addResourceTypes(array(
‘forms’ => array(
‘path’ => ‘forms’,
‘namespace’ => ‘Form’
),
‘models’ => array(
‘path’ => ‘models’,
‘namespace’ => ‘Model’
),
));

// Return to bootstrap resource registry
return $autoloader;
}

protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .’/helpers’);
}

protected function _initDoctype()
{
$this->bootstrap(‘view’);
$view = $this->getResource(‘view’);
$view->doctype(‘XHTML1_STRICT’);
}
}

project/public/index.php

<?php
// Define path to application directory
defined(‘APPLICATION_PATH’)
|| define(‘APPLICATION_PATH’, realpath(dirname(__FILE__) . ‘/../application’));

// Define application environment
defined(‘APPLICATION_ENV’)
|| define(‘APPLICATION_ENV’, (getenv(‘APPLICATION_ENV’) ? getenv(‘APPLICATION_ENV’) : ‘development’));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . ‘/../library’),
get_include_path(),
)));

/** Zend_Application */
require_once ‘Zend/Application.php’;

// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . ‘/configs/application.ini’
);
$application->bootstrap()
->run();

project/application/configs/application.ini

[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH “/../library”
bootstrap.path = APPLICATION_PATH “/Bootstrap.php”
bootstrap.class = “Bootstrap”
appnamespace = “Application”
resources.frontController.controllerDirectory = APPLICATION_PATH “/controllers”
resources.frontController.params.displayExceptions = 0
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH “/layouts/scripts/”

resources.db.adapter = “PDO_MYSQL”
resources.db.params.host = “localhost”
resources.db.params.username = “guestbook”
resources.db.params.password = “guestbook”
resources.db.params.dbname = “guestbook”

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1

project/application/controllers/GuestbookController.php

<?php
class GuestbookController extends Zend_Controller_Action
{

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

public function indexAction()
{
$guestbook = new Application_Model_GuestbookMapper();
$guestbook->fetchAll();
//var_dump($guestbook);
$this->view->entries = $guestbook->fetchAll();
}
}

project/application/models/Guestbook.php

<?php
class Application_Model_Guestbook
{
protected $_comment;
protected $_created;
protected $_email;
protected $_id;

public function __construct(array $options = null)
{
if (is_array($options)){
$this->setOptions($options);
}
}

public function __set($name, $value)
{
$method = ‘set’ . $name;
if ((‘mapper’ == $name) || !method_exists($this, $method)){
throw new Exception(‘Invalid guestbook property’);
}
$this->$method($value);
}

public function __get($name)
{
$method = ‘get’ . $name;
if ((‘mapper’ == $name) || !method_exists($this, $method)){
throw new Exception(‘Invalid guestbook property’);
}
return $this->$method();
}

public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach($options as $key => $value){
$method = ‘set’ . ucfirst($key);
if (in_array($method, $methods)){
$this->$method($value);
}
}
}

public function setComment($text)
{
$this->_comment = (string) $text;
return $this;
}

public function getComment()
{
return $this->_comment;
}

public function setEmail($email)
{
$this->_email = (string) $email;
return $this;
}

public function getEmail()
{
return $this->_email;
}

public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}

public function getCreated()
{
return $this->_created;
}

public function setId($id)
{
$this->_id = (int) $id;
return $this;
}

public function getId()
{
return $this->_id;
}
}

project/application/models/GuesbookMapper.php

<?php
class Application_Model_GuestbookMapper
{
protected $_dbTable;

public function setDbTable($dbTable)
{
if (is_string($dbTable)){
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract){
throw new Exception(‘Invalid table data gateway provided’);
}
$this->_dbTable = $dbTable;
return $this;
}

public function getDbTable()
{
if (null === $this->_dbTable){
$this->setDbTable(‘Application_Model_DbTable_Guestbook’);
}
return $this->_dbTable;
}

public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
’email’    =>    $guestbook->getEmail(),
‘comment’    =>    $guestbook->getComment(),
‘created’    =>    date(‘Y-m-d H:i:s’),
);

if (null === ($id = $guestbook->getId())){
unset($data[‘id’]);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data,array(‘id = ?’ => $id));
}
}

public function find($id, Application_Model_Guestbook $guestbook)
{
$result = $this->getDbTable()->find($id);
if (0 == count($result)){
return;
}
$row = $result->current();
$guestbook->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
}

public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
//var_dump($resultSet);
$entries = array();
foreach ($resultSet as $row){
$entry = new Application_Model_Guestbook();
$entry->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
$entries[] = $entry;
}
return $entries;
}
}

project/application/models/DbTable/Guestbook.php

<?php
class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
/** Table name */
protected $_name    = ‘guestbook’;
}

project/application/views/scripts/guestbook/index.phtml

<p><a href=”<?php echo $this->url(
array(
‘controller’ => ‘guestbook’,
‘action’ => ‘sign’
),
‘default’,
true) ?>“>Sign Our Guestbook</a></p>

Guestbook Entries: <br />
<dl>
<?php foreach ($this->entries as $entry): ?>
<dt><?php echo $this->escape($entry->email) ?></dt>
<dd><?php echo $this->escape($entry->comment)?></dd>
<?php endforeach ?>
</dl>

final URL to hit: http://project/guestbook

Leave a Reply

You must be logged in to post a comment.