Class for handling database connections

Asked

Viewed 781 times

1

Some time ago I created the class below to do operations of CRUD in the database.

Based on good programming practices, what would you change in class? and why?

<?php        
    Banco::getConexao();

    abstract class Banco {
        private static $database = 'mysql';
        private static $host = 'localhost';
        private static $banconome = 'testes';
        private static $user = 'root';
        private static $pass = '';
        private static $conexao = NULL;

        public function __construct() { }

        public function __destruct(){
            self::$conexao = NULL;
        }// __destruct

        public static function getConexao(){
            $dsn = self::$database.':host='.self::$host.';dbname='.self::$banconome;
            try{
                if(is_null(self::$conexao)):
                    self::$conexao = new PDO($dsn, self::$user, self::$pass);
                    self::$conexao->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                endif;
                return self::$conexao;
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }   
        }// getConexao

        public static function insert($tabela, $dados){
            $sql = 'INSERT INTO '.$tabela.' (';
            foreach($dados as $key => $value):
                $campos[] = $key;
                $tokens[] = '?';
                $valores[] = $value;
            endforeach;
            try{
                $sql .= implode(', ', $campos).') VALUES ('.implode(', ', $tokens).')';
                $query = self::$conexao->prepare($sql);
                $query->execute($valores);
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }
        }// insert

        public static function selectAll($tabela, $condicao = NULL){
            $sql = 'SELECT * FROM '.$tabela;
            if(!is_null($condicao)) $sql .= ' WHERE '.$condicao;
            try{
                $query = self::$conexao->prepare($sql);
                $query->execute();
                return $query->fetchAll(PDO::FETCH_OBJ);
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }
        }// selectAll

        public static function select($tabela, $campos, $condicao = NULL){
            $sql = 'SELECT '.$campos.' FROM '.$tabela;
            if(!is_null($condicao)) $sql .= ' WHERE '.$condicao;
            try{
                $query = self::$conexao->prepare($sql);
                $query->execute();
                echo $sql;
                return $query->fetchAll(PDO::FETCH_OBJ);
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }
        }// select

        public static function update($tabela, $dados, $condicao = NULL){
            $sql = 'UPDATE '.$tabela.' SET ';
            foreach($dados as $key => $value):
                $campos[] = $key.'=?';
                $valores[] = $value;
            endforeach;
            $sql .= implode(', ', $campos);
            if(!is_null($condicao)) $sql .= ' WHERE '.$condicao;
            try{
                $query = self::$conexao->prepare($sql);
                $query->execute($valores);
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }
        }// update

        public static function delete($tabela, $condicao = NULL){
            $sql = 'DELETE FROM '.$tabela;
            if(!is_null($condicao)) $sql .= ' WHERE '.$condicao;
            try{
                $query = self::$conexao->prepare($sql);
                $query->execute();
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }
        }// delete

        public static function countResult($tabela, $campo = NULL){
            !is_null($campo) ? $campo = $campo : $campo = '*';
            $sql = 'SELECT '.$campo.' FROM '.$tabela;
            try{
                $query = self::$conexao->prepare($sql);
                $query->execute();
                echo $sql;
                return count($res = $query->fetchAll(PDO::FETCH_OBJ));
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }
        }// countResult

        public static function erroLog($arquivo, $rotina, $mensagem){
            echo 'Aconteceu um erro com os seguintes Dados:<br />';
            echo '<b>No Arquivo = </b>'.$arquivo.'<br />';
            echo '<b>Na rotina = </b>'.$rotina.'<br />';
            echo '<b>Mensagem = </b>'.$mensagem.'<br />';
        }// erroLog

    }// Banco
?>

How the class is used:

$dados = array('nome' => 'Teste', 'senha' => '123');

$dados2 = array('nome' => 'Teste2', 'senha' => '1234');

$res = Banco::select('user', 'nome');

$res = Banco::selectAll('user', "nome LIKE '%teste%'");

$res = Banco::select('user', 'nome=Teste, senha=123');
  • 4

    If I were Victor, I’d take a look at http://medoo.in to get some ideas. Something I would change would be this bunch of statistical methods and make a dynamical object-oriented class, plus a better error function that uses logs instead of a simple echo

  • For example use of the working class there is no missing one Banco::getConexao() ?

  • No, the Banco::getConexao() is at the beginning of class Banco, ai it is not necessary to keep calling the connection.

1 answer

2


It would change in its class the following points:

  1. Remove the abstract class: The purpose of an abstract class is to be the basis of an inherited class. In your case it is being used to prevent the bank class from being instantiated. Even though it is not very well seen, I would wear Singleton in simple cases or any other Party (Dependency Injection for example).

  2. With the above change would also delete static calls (static) in all methods and would exchange the self:: for $this.

  3. In the method countResult would change the order of the if ternary comparison:

    // De
    !is_null($campo) ? $campo = $campo : $campo = '*';
    // Para
    $campo = !is_null($campo) : $campo ? '*';
    
  4. It would change the visibility of erroLog() for private, because this method is not useful outside the class

    private function erroLog($arquivo, $rotina, $mensagem)
    
  5. Another point that bothers me in your class is the use of try ... catch in all its methods. Any PDO error will not generate an error in PHP, but will display the HTML message, which can be difficult to notice depending on the layout of your page and can cause even more errors. Your class should throw to Exception forward and let a top layer handle the error on another try ... catch

  • In that part of try ... catch, I could have a class that only treated the exceptions? ai I called the passing class to exception for her?

Browser other questions tagged

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