mercredi 6 mai 2015

What is best practice when preparing insert statement for re-use within class?

I'm using PHP at the moment, but the question is just as valid for other languages I believe.

I have a class OfferProduct that represents a product within an offer. One offer can contain multiple products. This class has a function save() that prepares statement and executes it.

To avoid preparing a statement that already exist I added a private static variable to the class $isPreparedStatementDeclared. If isPreparedStatementDeclared is false the statement will be prepared, which happens the first time save() is called.

public function save() {
    global $db;

    if (!self::$isPreparedStatementDeclared) {
        $db->prepare('new_offer_product', 'INSERT INTO offer_product (' .
                'product_id, ' .
                'price_ex_vat, ' .
                'vat_percent, ' .
                'amount, ' .
                'discount_percent, ' .
                'free_text, ' .
                'qty_type, ' .
                'offer_id' .
                ')VALUES (' .
                '$1, ' .
                '$2, ' .
                '$3, ' .
                '$4, ' .
                '$5, ' .
                '$6, ' .
                '$7, ' .
                '$8)');

        self::$isPreparedStatementDeclared = true;
    }

    // Return bool result of query
    return ( $db->execute('new_offer_product', array(
                $this->productId,
                $this->priceExVat,
                $this->vatPercent,
                $this->amount,
                $this->discountPercent,
                $this->freeText,
                $this->qtyType,
                $this->offerId)));
}

Is this good practice?

It doesn't seem like a good solution to prepare the statement outside of this class, and then loop through every product and call save().

Maybe a separate class PreparedStatements where prepared statements are stored in a static array, and the class prepares statement if it hasn't already been prepared?

Aucun commentaire:

Enregistrer un commentaire