The ActiveRecord Pattern(2) サンプルコード

<< (1)アクティブレコードパターン - 目次に戻る - (3)独立したテスト >>
http://www.devshed.com/c/a/PHP/The-Active-Record-Pattern/1/の日本語訳です。

サンプルコード - The Active Record Pattern - Sample Code

データベース接続の議論はデータベースとアクセス層の双方の選択に依存します。この章と続く二つの章では人気のあるオープンソースのデータベースMySQL(http://www.mysql.com/)とADOdb(http://adodb.sf.net/)アクセス層を使用します。ADOdbはパフォーマンスがよく、さらに、Oracle OCIインタフェースを抽象化しており、PostgreSQLSybaseMySQL、その他のデータベースを単一の便利なPHP APIで使用できて、プログラミングとビジネスロジックだけに集中できるので、私のワークスペースの標準にしました。

Any discussion of database connectivity depends on choosing both a database and an access layer. This and the following two chapters use the popular open source database MySQL (http://www.mysql.com/) and the ADOdb (http://adodb.sf.net/) access layer. I established ADOdb as a standard in my workplace because it has excellent performance and it abstracts the Oracle OCI interface and interfaces to PostgreSQL, Sybase, MySQL, and other databases in a uniform, simple-to-use PHP API, allowing you to focus on your programming and business logic.

ここで紹介する考え方のほとんどは他のソリューションへも簡単に移植できるので、あなた方のデータベースとアクセス層への置き換えも簡単にできます。

Feel free to substitute you own database and access layer, as most of the concepts presented here readily port to other solutions.

アクティブレコードパターンを見る前に、基本的なデータベース接続を行いましょう。データベース接続のパラメータ(ホスト名やユーザ名、パスワード、データベース)の指定やデータベース接続オブジェクトの作成は、中心となる簡単なやり方があるのが理想的です。たいていの場合シングルトン(4章参照)で十分です。

Before looking at the Active Record pattern, let's start with basic database connectivity. It's ideal to have a central, simple way to specify connection parameters (the hostname, username, password, and database) and to create a database connection object. A Singleton (see Chapter 4) typically suffices.

以下はADDConnectionクラスのシングルトンなインスタンスを返すconn()メソッドを持つDBクラスです。

Here's a DB class with a conn() method that returns the Singleton instance of the ADOConnection class.

  // PHP5
  require_once 'adodb/adodb.inc.php';
  class DB {
    //staticクラスなので、コンストラクタが不要
    //static class, we do not need a constructor
    private function __construct() {}
    public static function conn() {
      static $conn;
      if (!$conn) {
        $conn = adoNewConnection('mysql');
        $conn->connect('localhost', 'username', 'passwd', 'database');
        $conn->setFetchMode(ADODB_FETCH_ASSOC);
      }
      return $conn;
    }
  }

DBクラスでデータベースの種類とデータベース接続に使う接続パラメータを制御できます。このコードは最初にADOdbライブラリをインクルードします(あなた方の環境に適したインクルードパスに変更してください)。DBのインスタンスの作成は不要なので、DBコンストラクタはprivateにしています。また、結果セットのオブジェクトが フィールド名 => 値の形式の連想配列として行を返すように、$conn->setFetchMode(ADODB_FETCH_ASSOC)の行で指定しています。連想配列の使用すればSQL文のSELECT節中のフィールドの順番にコードが影響を受けなくくなる(壊れにくくなる)ので、データベースの利用時に適用でる有力なベストプラクティスです。

The DB class allows you to control the type of database and the connection parameters used in connecting to the database. At the top, the code includes the ADOdb library (you may need to adjust the include path to suit your environment); The DB constructor is private since there's no need to ever create an instance of DB; And the line $conn->setFetchMode(ADODB_FETCH_ASSOC) instructs the result set object to return rows as associative arrays of field_name => value. Using an associative array is an important best practice to adopt in working with databases, so your code remains unaffected (less brittle) by the ordering of fields in SELECT clauses of your SQL statements.

アプリケーションの例として、ハイパーリンクのテーブルをメンテナンスするアクティブレコードオブジェクトを作りましょう。MySQLデータベースでハイパーリンクテーブルを作るには以下のようにします:

As an example application, let's create an Active Record object to maintain a table of hyperlinks. Here's the SQL to create the hyperlinks table in a MySQL database:

  define('BOOKMARK_TABLE_DDL', <<

<< (1)アクティブレコードパターン - 目次に戻る - (3)独立したテスト >>