I am working on a subquery library for CodeIgniter (link to project), which works by returning database objects that you can use instead of the normal $this->db object.
Originally, I was making new database objects each time:
$this->CI =& get_instance();
$db = $this->CI->load->database('', true);
But I then realized (or rather someone pointed out to me) that this would make a new database connection each time! So I decided to try to clone objects instead of making new ones.
I updated the code to look like so (link to full code):
class Subquery{
var $CI, $db;
function __construct(){
$this->CI =& get_instance();
$this->db = $this->CI->db; // Default database connection
}
function start_subquery(){
$newDatabase = clone $this->db;
// some more code
return $newDatabase;
}
}
I tested this, and it seems to work, but I’m not sure if this solves the problem. Does using clone make a new database connection, or does it use references internally and only keep one connection?
First off, the
=&is unnecessary and potentially harmful if you are not using PHP 4 (I assumeget_instancereturns an object).As for whether
clonecreates a new connection .. this depends on the DB implementation. As far as I can tell,PDOdoes not create an additional connection when it’s cloned. If you want to test this, create a small script that runsstart_subqueryto some effect and then sleeps for a decent amount of time. Connect to mysql and run:If it’s more than 2 (your connection to run the query and the one from your script) then an additional connection is being made for some reason.
As for whether you should clone the DB, I don’t know why you would want to, but I don’t really know the use case for this class nor do I know much about CI.