Thursday, July 28, 2011

Introduction to Zend_Db

Comments on Chapter 6 of "Easy PHP Websites With The Zend Framework (2011)" by Jason Gilmore. <http://gamenomad.wjgilmore.com/about/book>

This is the chapter where you interact with database tables using Zend_Db. You need to set up a database and a ZF project that interacts with it to follow the examples in the book. Rather than use the scaled down database table the author defines on page 89, it is better to create and populate the database tables for the gamenomad website. (Instructions for doing so are provided by the author in INSTALL.txt. See earlier post regarding changes to the seed.php script and cli.php)

Once you've populated and updated the tables (see other scripts within applications/scripts), you can export copies of the "games", "platforms" and "ranks" tables as SQL files. Import these tables into your scaled down version of the games database (mine is named "gilmore").

Configure your application.ini file using the ZF CLI as described on page 89:

zf configure db-adapter \
'adapter=PDO_MYSQL&host=%&username=user&password=pass&dbname=gilmore' development

The following should now show up in the development section:

resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.username = "user"
resources.db.params.password = "secret"
resources.db.params.dbname = "gilmore"

You're now ready to create a Games, GamesRow and Platforms DbTable models using the ZF CLI as described in the book. Later, you'll create relationships between these table models, but you can skip it for now.

Some of the field names in the sample code differ from the field names in the "games" table. The scripts provided below are revised from those included in the book to match the actual table names.

// This code is written within indexAction in IndexController
// application/controllers/IndexController.php

public function indexAction()
{
$gamesTable = new Application_Model_DbTable_Games();

$select = $gamesTable->select()->where('asin =?', 'B002BSA20M');
$this->view->game = $gamesTable->fetchRow($select);
}

// This code is written in application/views/scripts/index/index.phtml

<h3><?php echo $this->game->name; ?></h3>
<img src="<?php echo $this->game->medium; ?>" style="float: left;" />
<p>
Release date: <?php echo date("F j, Y", strtotime($this->game->rel)); ?>
</p>

You should get close to that shown in Figure 6.1 on page 87.

Hope it works for you!

1 comments:

PHP Developer said...

thanks for sharing such a wonderful information...