三、生成DAO工件
下面我们说明一个使用名为bookstore的数据库的DAO工件的生成进程。该数据库含有一个表,表的名称为books,其结构如图2所示。
图 2. 表Books的结构:该图展示了数据库bookstore中的表Books中的一些样本数据及其结构
为了创建如图2所示的表,可以执行如下所示的SQL语句:
create table books
(id int not null auto_increment primary key,
title varchar(50),
author varchar(50),
yearofpublication int,
publisher varchar(50),
price int);
(id int not null auto_increment primary key,
title varchar(50),
author varchar(50),
yearofpublication int,
publisher varchar(50),
price int);
生成该DAO工件之前,需要使用以下INSERT语句向表books中填入五条记录:
insert into books values(1,"Annabel Lee",
"Edgar Allan Poe",1849,"The Literature Page",256);
insert into books values(2,"The Ballad of Reading Gaol",
"Oscar Wilde",1898,"The Literature Page",475);
insert into books values(3,"The Sonnets",
"Edgar Allan Poe",1602,"The Literature Page",300);
insert into books values(4,"Winnetow",
"Karl May",1956,"The truth",123);
insert into books values(5,"JBoss Tools 3",
"Anghel Leonard",2009,"Packt",569);
"Edgar Allan Poe",1849,"The Literature Page",256);
insert into books values(2,"The Ballad of Reading Gaol",
"Oscar Wilde",1898,"The Literature Page",475);
insert into books values(3,"The Sonnets",
"Edgar Allan Poe",1602,"The Literature Page",300);
insert into books values(4,"Winnetow",
"Karl May",1956,"The truth",123);
insert into books values(5,"JBoss Tools 3",
"Anghel Leonard",2009,"Packt",569);
创建并填充好有关数据库和表之后,我们就可以执行DAO Generator来创建DAO工件了。若要运行该生成器,需要执行下列操作:
⒈ 在ConnectionProperty类中设置连接属性:host、user、password和database。
2. 运行generated.php脚本。
3. 我们将得到如下所示的输出结果:
generated/class/dto/Books.class.php
varchar(50)
varchar(50)
varchar(50)
varchar(50)
int(11)
int(11)
varchar(50)
varchar(50)
int(11)
int(11)
generated/class/mysql/BooksMySqlDAO.class.php
varchar(50)
varchar(50)
int(11)
varchar(50)
int(11)
generated/class/dao/BooksDAO.class.php
generated/include_dao.php
generated/class/dao/DAOFactory.class.php
varchar(50)
varchar(50)
varchar(50)
varchar(50)
int(11)
int(11)
varchar(50)
varchar(50)
int(11)
int(11)
generated/class/mysql/BooksMySqlDAO.class.php
varchar(50)
varchar(50)
int(11)
varchar(50)
int(11)
generated/class/dao/BooksDAO.class.php
generated/include_dao.php
generated/class/dao/DAOFactory.class.php
4. 输出结果中的最后三行是生成的类的名称,这些类被放入phpdao-1.7目录的新建子目录中。
为应用程序生成的这三个类都用到表books。第一个类位于generated/class/dto/Books.php文件中,它定义了一个表示表books的对象:
<?php
/**
* Object represents table 'books'
*
* @author: http://phpdao.com
* @date: 2009-08-10 22:50
*/
class Books{
var $id;
var $title;
var $author;
var $yearofpublication;
var $publisher;
var $price;
}
?>
/**
* Object represents table 'books'
*
* @author: http://phpdao.com
* @date: 2009-08-10 22:50
*/
class Books{
var $id;
var $title;
var $author;
var $yearofpublication;
var $publisher;
var $price;
}
?>
第二个类位于generated/class/dao/BooksDAO.php文件中(请参阅清单1),它是一个接口,定义了针对表books的各种各样的操作。
第三个类,也是最后一个类位于/class/mysql/BooksMySqlDAO.php文件中,它实现了前面的接口。您可以在相应的文件夹中看到这个类,由于它很长,所以这里就不列出来了。