Reputation: 4519
I have a singleton class for PDO, below is the relevant part of the class
public static function getInstance( $config )
{
if ( ! isset(self::$instance))
self::$instance = new self( $config );
return self::$instance;
}
public function __construct( $config )
{
self::$start = self::timer();
try
{
$host = $config['host'];
$dbname = $config['name'];
$user = $config['user'];
$password = $config['password'];
self::$objInstance = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8",
"$user",
"$password",
array(PDO::ATTR_PERSISTENT => true)
);
self::$objInstance -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch (PDOException $e)
{
//need to log for security
die('PDO CONNECTION ERROR: ' . $e->getMessage() . '<br/>');
}
}
public static function closeConnection ( )
{
try
{
self::$objInstance = null;
}
catch (PDOException $e)
{
//OPTIMIZE**************************** to do
//file_put_contents("log/dberror.log", "Date: " . date('M j Y - G:i:s') . " ---- Error: " . $e->getMessage().PHP_EOL, FILE_APPEND);
die($e->getMessage());
}
self::$end = self::timer();
}
So here everything works fine, but when I call the static closeConnection()
after any DB operation, it makes the PDO instance null, which is fine but again calling the PDO instance gives error, beacuse PDO is now null due to calling closeconnection. My question is how to deal with closing the PDO in singleton class ?
Upvotes: 0
Views: 1500
Reputation: 7880
From the documentation:
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning
NULL
to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
With a singleton, the entire life of the connection should be controlled from the singleton itself. As such, I would rely on the documented automatic closing of connections and not expose a method to close the connection at all (for the same reasons the constructor should not be exposed).
Upvotes: 0
Reputation: 15464
Change
self::$objInstance = null;
into
self::$instance = null;
Because you trying remove PDO object instead of singleton object.
Upvotes: 1