开发者

Should I be closing a PDO database connection inside a method or on a calling page?

I can't seem to find an answer for this. I know to close a PDO connection you need to use $db=NULL; I have been using dependency injection to use access my database connection within classes. Should I be using $db=NULL; inside the method, or should I be using it on the page calling the query?

like so:

public function find_all() {
     connect to $db;
       //run query
        $db = NULL;
          return query
}

or should it be like this:

$thing = Me开发者_开发技巧thod::find_all();
 //display results
 $thing = NULL;

i have been using the first method, and haven't gotten any errors, but i want to make sure that i'm doing it the correct way. Thanks.


All PHP connections are closed automatically when the script ends. However, it's not a bad practice to manually "dispose" no longer required objects.


Likely your dependency injection container will be keeping a copy of your database connection, so while unset($db) or $db = null could be used to close it normally, this will only work if it is the last reference.

Also, it may make more work to open and close your database connection for every 'find' method, unless you know there will only be at most one query for any page.

Your 2nd method will free up some space, but unless '$thing' is your database connection or contains the last reference to your database, it wouldn't be closing your database connection either.


its a good practice to close all connections at the end of he script, how ever if your script makes alot of connections then its better to use a persistent connection and dont forget to close them else your DB will have too many connections open.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜