Isn’t it right to connect the database only once and then go through the records?

Asked

Viewed 287 times

1

<?php
class Usuario {

    private $login;
    private $senha;
    private $admin;

    //variaveis internas
    private $bd; //conexão com o banco
    private $tabela; //nome da tabela

    public function __construct() {
        $this->bd = new BD();
        $this->tabela = "usuario";
    }


    public function listar($complemento = "") {
        $sql = "SELECT * FROM $this->tabela ".
                $complemento;

        $resultado = pg_query($sql);
        $retorno = NULL;
        //percorre os registros
        while ($reg = pg_fetch_assoc($resultado)) {
            //transforma em objetos categoria
            $obj = new Usuario();                  // mudar
            $obj->login = $reg["login"];
            $obj->senha = $reg["senha"];
            $obj->admin = $reg["admin"];
            //adiciona a variavel de retorno
            $retorno[] = $obj;
        }
        return $retorno;
    }
}
?>

In that part:

while ($reg = pg_fetch_assoc($resultado)) {
    //transforma em objetos categoria
    $obj = new Usuario();                  // mudar
    $obj->login = $reg["login"];
    $obj->senha = $reg["senha"];
    $obj->admin = $reg["admin"];
    //adiciona a variavel de retorno
    $retorno[] = $obj;
}

When creating an object of type Usuario within the while, Won’t it be connecting all the time in the bank? no construct it is doing starting the connection with the bank, is not it? it works, but the correct is not to connect the bank only once and then go through the records?

public function __construct() {
    $this->bd = new BD();
    $this->tabela = "usuario";
}

BD-class:

class BD {
    public function __construct() {
        pg_connect("host=localhost user=postgres 
            password=123 dbname=ss port=5432")
                or die("Erro ao conectar ao servidor");
    }
}

1 answer

2

Yes, the correct thing would be to establish the connection only once. Just don’t put the connection in the constructor and do the part.
Or as @chambelix said, use the bd variable as Static. And in that case it would not be necessary to instantiate the class to use the comic.

By the way, is this working? It shouldn’t. Unless you’ve already opened the connection before using this class.

Gets the code:

<?php
class Usuario {

    private $login;
    private $senha;
    private $admin;

    //variáveis internas  
    //private $bd;           // sem static

    private static $bd;                          
    private $tabela; //nome da tabela

    public function __construct() {
        $this->tabela = "usuario";
        if(!isset(self::$db)) {       //sem static retirar
            self::$db = new DB();     //estas linhas
        }
    }

    //sem static
    //private function connect() {
    //    
    //    $this->bd = new BD();
    //    return $this->bd;
    //}

    public function listar($complemento = "") {
        $sql = "SELECT * FROM $this->tabela ".
                $complemento;   

        //sem static
        //$connection = $this->connect();                       
        //$resultado  = pg_query($connection, $sql);

        $resultado  = pg_query(self::$db, $sql);
        $retorno    = NULL;
        //percorre os registros
        while ($reg = pg_fetch_assoc($resultado)) {
            //transforma em objetos categoria
            $obj = new Usuario();                 
            $obj->login = $reg["login"];
            $obj->senha = $reg["senha"];
            $obj->admin = $reg["admin"];
            //adiciona a variavel de retorno
            $retorno[] = $obj;
        }
        return $retorno;
    }
}
?>

Notice that I used the BD connection to make the query as recommended in documentation:

Note: Connection is an optional parameter for pg_query(). If Connection is not set, the default connection will be used. The connection default is the last connection made by pg_connect() or pg_pconnect(). While Connection may be omitted, this is not recommended since can be a cause of hard-to-find errors in your script.

  • But in case he has to implement Users and Administrators still new BD() will be instantiated 2 times creating 2 connections.

  • 1

    @Papacharlie to which situation you refer?

  • @chambelix done, was this your idea?

  • @Jorgeb. look see my issue. passes the comments to a definitive code.

  • @Jorgeb. and definitely goes from public Static to private Static clearly.

  • @chambelix is good for you? : P

  • @Jorgeb. Yeah... done.. =)

  • @chambelix, @Jorgeb., you applied a Singleton in what would be a template. It means you can invoke $usuarios-> listar(...) or any other class method Users that will be guaranteed only 1 instance of DB. But if for some reason the controller requests another model - $blogs-> ultimos(...) - this does not yet have self::$db and will make a NEW connection to DB independently of the previous...

  • 1

    If the Singleton be applied in the DB, would work properly, even ignoring the discussions of the issues it brought as help. The class DB must ensure that it will make a single connection with DB-X or DB-Y.

  • 1

    You’re right @Papacharlie.

  • @Jorgeb. this is an old subject, so I recommended the 2 questions as reference. If you play this Singleton in DB, can make a connector very simple and efficient.

  • @Papacharlie in the context of the self question/answer::$db will always have the instance of DB because it is STATIC, so I don’t understand your point. By indicating that there may be a call $blogs->ultimos(...) you will not have the same access to the self::$db, which I cannot agree with. I’m sorry but maybe I misunderstood your point of view.

  • 1

    @chambelix what Papacharlie means is that this BD instantiation should be out of class.

  • 1

    @Jorgeb. if that is the case and in a context of several classes I agree... but in the context of the question an instance for the class I think is fine.

Show 9 more comments

Browser other questions tagged

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