|
Posted by ZeldorBlat on 05/05/06 18:40
Don Sami wrote:
> I've got a question about reusing object instantances or to creating
> new ones. Which is better? Pros and Cons such as open database
> connections, overhead, etc?
>
> Right now I am using a Database class for all MySQL operations such
> as:
>
> $db = new MySQL();
>
> $db->query("INSERT INTO log (tstamp) VALUE (NOW())");
>
> $db->query("INSERT INTO orders (amount) VALUE ('10.00')");
> $order_id = $db->fetchLastInsertId();
>
> Ok now I am still in the same PHP file but should I create a new
> database as....
>
> $db->query("INSERT INTO orders_lineitems (order_id, item)
> VALUES ($order_id, 'apple pie');
>
> or it is better to create a new instance and then do the same thing...
>
> $new_db = new MySQL();
> $new_db->query("INSERT INTO orders_lineitems (order_id, item)
> VALUES ($order_id, 'apple pie');
>
>
> Also I am thinking if there is an error executing the 2nd INSERT INTO
> orders query then $db->fetchLastInsertId() would get populated with
> the lastInsertId of the INSERT INTO log query. So the $order_id gets
> populated with log_id which I don't want. So perhaps using a new
> instance is best, am I right or wrong????
>
> execute
>
> TIA
A couple things:
According to the documentation, mysql_insert_id() returns:
"The ID generated for an AUTO_INCREMENT column by the previous INSERT
query on success."
So, regardless of whether the insert statement was successful, the
function will return the auto id from the /last/ insert statement, if
available.
Second, calling mysql_connect() will reuse an existing connection if
available. So it really doesn't matter how many objects you have -- if
they're connecting to the same database with the same parameters an
existing link will be reused.
I typically make my database object a singleton (only one instance can
exist at a time). So, all I need to do, regardless of what scope I
might be in, is something like this:
$db = DB::get();
$db->execute($query);
....
If no database has been instantiated yet, this get() method will create
one, store it, and return it. If an object has already been created,
get() returns the instance that was previously stored. Of course how
you actually implement singletons is up to you.
Navigation:
[Reply to this message]
|