1

prepare() によって返された PDOStatement を何らかのクラス変数に保存し、同じ呼び出しを実行するときに再準備するのではなく、そのステートメント オブジェクトを再利用するのは効率的でしょうか?

Class QueryClass {
    public static $getSomeData;
}

Class Foo {

    $pdo = $pdo (PDO)
    $id;
    $first_name;
    $last_name;
    $email;
    $city;

    public function __construct(PDO $pdo, $id) {
        $this->pdo = $pdo;
        $this->id  = $id;
    }

    public function searchDB(Array $find) {

        $query  = "SELECT " . prepare_array($find);
        $query .= "FROM some_database ";
        $query .= "WHERE id = ?";

        // Option 1.) Prepare Normally
        $statement = $this->pdo->prepare($query);

        // Option 2.) Prepare conditionally depending on what the query
        // was the last time the method was called. So it should only be called
        // when either (A) The method has never been called OR (B) The user
        // has changed the query string by entering different data in the
        // $find parameter

        if (!QueryClass::$getSomeData instanceof PDOStatement
            || QueryClas::$getSomeData->queryString != $query)
        {
            QueryClass::$getSomeData = $this->pdo->prepare($query);
        }

        // Executing Option 1
        $statement->execute(Array($this->id));

        // Exectuting Option 2
        QueryClass::$getSomeData->execute(Array($this->id));  
    }
}

// And then using like this (I know that I havent actually created the PDO, just assume
// that I'm providing it). The second searchDB() call should use the same PDOStatement
// object created when the first object used it

$var  = new Foo($pdo, 5);
$var2 = new Foo($pdo, 10); 

$var->searchDB(Array('first_name', 'last_name', 'email'));
$var2->searchDB(Array('first_name', 'last_name', 'email'));

// Then makeing a call like this would cause the method to re-prepare the
// PDOStatement because the params provided are different

$var2->searchDB(Array('first_name', 'city'));

これは、クエリまたはメソッドが呼び出されるたびに新しいステートメントを準備するよりも効率的ですか?

4

0 に答える 0