I'm developing a small project using php with standard mvc and the smarty template engine. I made a connection class without applying any pattern and it looks like this:
Class Conexao extends Config {
private $bd_host;
private $bd_user;
private $bd_user_pass;
private $bd_base;
private $conexao;
function __construct() {
$this->bd_host = self::BD_HOST;
$this->bd_user = self::BD_USER;
$this->bd_user_pass = self::BD_USER_PASS;
$this->bd_base = self::BD_BASE;
try {
if (is_null($this->conexao)) {
$this->conectar();
}
} catch (PDOException $e) {
echo "ERROR GERADO AO CONECTAR COM BD: " . $e->getMessage();
}
}
private function conectar() {
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"];
$this->conexao = new PDO("mysql:host={$this->bd_host};dbname={$this->bd_base}", $this->bd_user, $this->bd_user_pass, $options);
}
function executeSQL($query, array $params = NULL) {
$this->obj = $this->getConexao()->prepare($query);
if (!empty($params)) {
return $this->obj->execute($params);
}
return $this->obj->execute();
}
function getConexao() {
return $this->conexao;
}
}
In my MODEL classes, when I need to do some operation with the database, I'm instantiating it and using it more or less as follows:
function registrarRemessaBd($time_insert){
$query = "INSERT INTO caf_remessa (time_insert) VALUE (?)";
$params = array($time_insert);
$conexao = new Conexao();
$conexao->executeSQL($query, $params);
return $conexao->getConexao()->lastInsertId();
}
Is it wrong to use this way? or should I use some standard for the connection such as singleton? What problems could I have if I use it that way?