Close PDO connection

Asked

Viewed 8,457 times

5

I have worked with other languages before working with PHP and in some the framework when you opened a connection with the database was good to finish it, in PDO so I realized there is a function in the PDO class that closes this connection. Is there any way in the PDO of close the connection with the bank?

2 answers

8


Look, the simplest impossible:

$pdo = null;

of course this is not necessary because the connection is automatically closed after the script execution

0

Despite not having much relationship with original doubt, it is worth commenting.

As you said you saw in a framework, almost absolute certainty (goes that...) that this was Object-Oriented and in these cases, a PDO implementation needs to have the property where the instance of the PDO object itself destroyed so that the connection logic works by connecting only once.

Roughly the same way:

abstract class Driver {

    protected $conn;

    public function getConnection() {

        if( $this -> conn === NULL ) {

             $this -> connect();
        }

        return $this -> conn;
    }

    abstract public function connect();

    abstract public function disconnect();
}

class PDO extends Driver {

    public function connect() {

        $this -> conn = new PDO( /** .. */ );
    }

    public function disconnect() {

        $this -> conn = NULL;
    }

}

Note: Not taken into account namespaces, interfaces or even Object Orientation paradigms to simplify to the maximum.

Thus, given the flow of the vertical and increasing Request, a connection object defined, say, in an Application Controller can be used in an Action Controller or in a Model without risk of data loss.

And in the case of PDO at least it is very important because part of the operations are performed in PDO and part in Pdostatement and any improper re-connection between one step and another can, for example, generate an empty query error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.