【編集・更新】
状況を説明させてください。私は3つのファイルを持っています:
以下はdb.class.phpです。呼び出されると、コンストラクタで DB に接続し、デストラクタで接続を閉じます。query() メソッドに気付いた場合、それは現時点では単純な静的 INSERT です。
<?php
//
// Class: db.class.php
// Desc: Connects to a database and runs PDO queries via MySQL
// Settings:
error_reporting(E_ALL);
////////////////////////////////////////////////////////////
class Db
{
# Class properties
private $DBH; // Database Handle
private $STH; // Statement Handle
# Func: __construct()
# Desc: Connects to DB
public function __construct()
{
// Connection information
$host = 'localhost';
$dbname = 'removed';
$user = 'removed';
$pass = 'removed';
// Attempt DB connection
try
{
$this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Successfully connected to the database!';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
# Func: query(sql statement)
# Desc: Sends a query to the DB
public function query($sql_statement)
{
$sql = array(':color' => $sql_statement);
$this->STH = $this->DBH->prepare("INSERT INTO color_table (color) value ( :color )");
$this->STH->execute($sql);
}
# Func: __destruct()
# Desc: Disconnects from the DB
public function __destruct()
{
// Disconnect from DB
$this->DBH = null;
echo 'Successfully disconnected from the database!';
}
}
?>
以下はcolors.class.phpです。今のところ、挿入機能しかありません。私がやろうとしているのは、基本的に db.class.php から query() 関数にあるものをリッピングし、それを insertColor() 関数に入れ、挿入、削除、削除のいずれであっても SQL ステートメント全体を渡すことです。または query() 関数に更新します。
<?php
//
// Class: colors.class.php
// Desc: Provides methods to create a query to insert,
// update, or delete a color from the database.
////////////////////////////////////////////////////////////
class Colors
{
# Class properties
protected $db;
# Func: __construct()
# Desc: Passes the Db object so we can send queries
public function __construct(Db $db)
{
$this->db = $db;
}
# Func: insertColor()
# Desc: Sends an INSERT querystring
public function insertColor($color)
{
$this->db->query($color);
echo 'Inserted color:' . $color;
}
}
?>
以下に、上記のすべてがインスタンス化され、実装されているcolors.phpがあります。ここで、実際にデータベースに挿入したい色を渡します。
<?php
Require('db.class.php');
Require('colors.class.php');
$db = new Db;
$colors = new Colors($db);
$colors->insertColor('TestColor'); // Passing the color here to be put into an insert statement
?>
私が基本的に立ち往生しているのは、colors.class.php に PDO ステートメントを作成させ、実行準備ができたら db.class.php query() メソッドに渡そうとしていることです。現在、PDO ステートメントは query() メソッドで単純に定義されていますが、これを回避しようとしています。基本的に、query() メソッドから取得したものを取り出し、それを Colors クラスの 3 つのメソッドに分割します。1 つは挿入、更新、および削除用です。
ただし、私は OOP プログラミングにかなり慣れていないため、すべての構文に問題があり、これが良いアプローチであるかどうかもわかりません。詳細や情報が必要な場合はお知らせください。