4
I am building a simple webservice and PHP + JSON where I have 2 tables and I intend to perform CRUD operations. It is possible that the webservice is in the medium term consumed by many devices at the same time, which in my opinion can lead to many simultaneous connections. The server has a limit of active connections determined by the people of the infra (I think they are 30). My question is, I use the PDO to open the connection and the connection is called by a static method, in each request I receive the ID of the user who makes the query, Is it better to change the way the connection is performed by always opening and closing each query or will this not affect the number of open connections? Follow an excerpt from my connection class:
class Database extends PDO {
/**
* @var array Array of saved databases for reusing
*/
protected static $instances = array();
/**
* Static method get
*
* @param array $group
* @return \helpers\database
*/
public static function get ($group = false) {
// Determining if exists or it's not empty, then use default group defined in config
$group = !$group ? array (
'type' => 'mysql',
'host' => 'localhost',
'name' => 'banco',
'user' => 'root',
'pass' => 'toor'
) : $group;
// Group information
$type = $group['type'];
$host = $group['host'];
$name = $group['name'];
$user = $group['user'];
$pass = $group['pass'];
// ID for database based on the group information
$id = "$type.$host.$name.$user.$pass";
// Checking if the same
if(isset(self::$instances[$id])) {
return self::$instances[$id];
}
try {
// I've run into problem where
// SET NAMES "UTF8" not working on some hostings.
// Specifiying charset in DSN fixes the charset problem perfectly!
$instance = new Database("$type:host=$host;dbname=$name", $user, $pass);
$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Setting Database into $instances to avoid duplication
self::$instances[$id] = $instance;
return $instance;
} catch(PDOException $e){
//in the event of an error record the error to errorlog.html
Logger::newMessage($e);
logger::customErrorMsg();
}
}