Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 15 ■ INTRODUCTION TO THE ZEND FRAMEWORK^223

Listing 15-5. Database Connection Information for Bootstrapping (in index.php)

$params = array (
'username' => 'demouser',
'password' => 'demopass',
'dbname' => 'demodb'
);

$db = Zend_Db::factory('PDO_PGSQL', $params);

Zend_Db_Table::setDefaultAdapter($db);

The setDefaultAdapter() call ensures that any future attempt to connect to a database
without explicit connection information will use this connection information. This allows any
Zend_Db_Table instances to worry about the structure of the tables and not about where they
need to connect. It also provides a convenient and centralized configuration point.

Creating the Customers Model, Controller, and View
Now you can create a Zend_Db_Table-derived model that will interact with your database table:

> pico application/models/Customers.php

Add the code shown in Listing 15-6.

Listing 15-6. Customers Model (application/models/Customers.php)

<?php
class Customers extends Zend_Db_Table {
protected $_name = 'customers';
protected $_primary = 'customer_id';
}

Next, in your controller directory, create a new action controller to list all your customers.

> pico –w application/controllers/CustomersController.php

Add the code shown in Listing 15-7.

Listing 15-7. Customers Controller (application/controllers/CustomersController.php)

<?php
class CustomersController extends Zend_Controller_Action {
public function indexAction() {
$table = new Customers();
$this->view->customers = $table->fetchAll();
}
}

McArthur_819-9C15.fm Page 223 Thursday, February 28, 2008 7:44 AM

Free download pdf