DAOクラスの概要
以下、重要なDAOクラスについて簡単に説明していきます。
ConnectionFactoryクラス:これはデータベースと密接に連動するクラスです。この「ファクトリ」クラスにはデータベースへの接続をオープンするという役割があります。データベースへの接続はgetConnectionメソッドで行われ、このメソッドはデータベース名とユーザー名/パスワード資格情報を表す3つの引数を取ります。これらの引数はConnectionPropertyクラスのPOJOスタイルでマップされます。Connectionクラス:このクラスはデータベースへの単一の接続を表します。実際の接続はConnectionコンストラクタでConnectionFactoryクラスから取得します。Transactionクラス:このクラスはデータベースへのトランザクション操作を可能にする一群の関数をカプセル化しています。このクラスはヘルパークラスArrayListを通じてトランザクションの配列を提供します。ArrayListはPHP配列に対してコレクションをシミュレートするクラスです。これらのトランザクションはConnectionが提供する接続を使用します。TransactionクラスはgetCurrentTransaction関数によって現在のトランザクションへのアクセスも提供します。QueryExecutorクラス:QueryExecutorクラスはSQLステートメントを実行するための関数を提供します(正確にはCRUD構文を実装する関数を提供します)。execute関数はSQLのSELECTステートメントを実行し、executeUpdate関数はSQLのUPDATE、DELETE、INSERTステートメントを実行します。{databasename}MySqlDAOクラス:DAOジェネレータはこのクラスを生成します。このクラスは特定のデータベースのための一連のDAO関数を提供します。生成されたクラスはgenerated/class/mysqlフォルダに格納され、データベース名に接尾辞「MySqlDAO」を付けたものがクラス名になります。このクラスの生成方法と使用方法は後ほど説明します。
static public function getConnection() {
$conn = mysql_connect(ConnectionProperty::getHost(),
ConnectionProperty::getUser(),
ConnectionProperty::getPassword());
mysql_select_db(ConnectionProperty::getDatabase());
if(!$conn){
throw new Exception('could not connect to database');
}
return $conn;
}
public function Connection() {
$this->connection = ConnectionFactory::getConnection();
}
このクラスには接続のクローズとSQLクエリの実行という役割もあります。
public static function execute($sqlQuery){
$transaction = Transaction::getCurrentTransaction();
if(!$transaction){
$connection = new Connection();
}else{
$connection = $transaction->getConnection();
}
$query = $sqlQuery->getQuery();
$result = $connection->executeQuery($query);
if(!$result){
throw new Exception(mysql_error());
}
$i=0;
$tab = array();
while ($row = mysql_fetch_array($result)){
$tab[$i++] = $row;
}
mysql_free_result($result);
if(!$transaction){
$connection->close();
}
return $tab;
}
public static function executeUpdate($sqlQuery){
$transaction = Transaction::getCurrentTransaction();
if(!$transaction){
$connection = new Connection();
}else{
$connection = $transaction->getConnection();
}
$query = $sqlQuery->getQuery();
$result = $connection->executeQuery($query);
if(!$result){
throw new Exception(mysql_error());
}
return mysql_affected_rows();
}
QueryExecutorクラスと{databasename}MySqlDAOクラスはSqlQueryというヘルパークラスを使用します。SqlQueryはSQLステートメントを表現および格納するための関数をカプセル化しています。
次に例を見ながら説明していきます。
