0

I am doing project using mongodb and zendframework 2 so here I create connection in the constructor

private $conn;

public function __construct(){
    $this->conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
}

It contain several actions to perform database operations like createdb, dropdb, renamedb like wise. so I close that connection within the __distruct() method

public function __destruct(){
    $this->conn->close();
}

my code works fine. but I would like to know is this ok?

user2047701
  • 31
  • 1
  • 1
  • 7

1 Answers1

0

PHP closes database connections automatically.

You can read more about this in this post

however read this

quote: "Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."

So basically, in case you have tons of things going in and out of the database, then yes, you might want to close right after.

In my opinion it is rather optional and your own choice wether to kill the process or not.

Community
  • 1
  • 1
Tikkes
  • 4,599
  • 4
  • 36
  • 62