How to reuse the connection in the subclass?

Asked

Viewed 158 times

4

Colleagues, I have a connection class:

class Conecta
{
    private $Servidor = '127.0.0.1';
    private $Usuario = 'root';
    private $Senha = 'senha';
    private $Banco = 'banco';

    // Protegido
    protected $Conecta;

    // Faz a conexão
    public function conectar(){

$this->Conecta = mysqli_connect($this->Servidor,$this->Usuario,$this->Senha,$this->Banco);
}

And I have a class of methods:

    class Metodos extends Conecta
    {
       // Primeiro método
      public functionPrimeiro(){
           $conectar = new Conecta();
            $conectar->conectar();

    $sql = mysqli_query($conectar->conectar(), "MINHA QUERY");
    }

    // Segundo método
      public functionSegunda(){
           $conectar = new Conecta();
            $conectar->conectar();

    $sql = mysqli_query($conectar->conectar(), "MINHA QUERY");
    }
}

Notice that within each method I use:

   $conectar = new Conecta();
    $conectar->conectar();

Would there be some way I wouldn’t use within each method or might just be that way?

3 answers

6

You can decouple this code and delete the inheritance. Start with a connection class that opens the connection to the bank as soon as it is instantiated:

class Conexao {

    // (...)

    // Tudo o que tinha na sua classe Conecta,
    // + o construtor abaixo
    function __construct() {
        $this->conectar();
    }

    // Se tem coisa específica do mysqli aqui,
    // pode ser interessante abstrair pelo menos
    // um método genérico de query. A ideia é
    // centralizar aqui tudo que lida direto com mysqli.
    public function query($sql) {
        $qry = mysqli_query($this->Conecta, $sql);
        return mysqli_fetch_all($qry, MYSQLI_ASSOC);
    }

}

In the method class, you inject the connection, also using the constructor:

class Dados {

    // Conexão guardada aqui
    protected $conexao;

    // Construtor: guarda a conexão
    function __construct($conexao) {
        $this->conexao = $conexao;
    }

    // Um método qualquer que usa o BD
    public function pegaDados() {
        return $this->conexao->query("MINHA QUERY");
    }
}

And you wear it like this:

$bd = new Dados(new Conexao());
var_dump($bd->pegaDados());
  • Hello bfavaretto, unfortunately I can not uncouple, because in other parts of the system is already using this way.

  • 2

    @Jose.Marcos I’m sorry, but your code is so wrong, I would rethink it and redo where I had to change.

  • Enjoy while you can, because the POO is basically about reusing codes.

  • Hello bigown, I agree with you, but unfortunately the system was already ready here in the company and if I change now, I would have to redo it almost completely and it would take time.

4


Modify the "Connect" class to:

class Conecta
{
    private $Servidor = '127.0.0.1';
    private $Usuario = 'root';
    private $Senha = 'senha';
    private $Banco = 'banco';

    // Protegido
    protected $Conecta;

    // Realiza a conexão no construtor 
    public function __construct()
    {
        $this->Conecta = mysqli_connect($this->Servidor,$this->Usuario,$this->Senha,$this->Banco);
    }
}

To use within your "Methods" class, simply do:

class Metodos extends Conecta
{
    // Primeiro método
    public functionPrimeiro()
    {
        $result = mysqli_query($this->Conecta, "MINHA QUERY");
    }

    // Segundo método
    public functionPrimeiro()
    {
        $result = mysqli_query($this->Conecta, "MINHA QUERY");
    }
}

Despite being a functional solution, I recommend that you accept the @bfavaretto board, if you want to uncouple even more use PDO!

Hug.

  • Hi Hizer. When I put __Construct, the page went blank.

  • Hello! You have an example from your page?

  • 1

    Looking at your code, it might be interesting to leave another method, identical to Construct but with the name "connect", so you ensure compatibility with your legacy code! Hug!

  • Hizer Bingo. Perfect. Based on your idea, I created a method called connect(); Thank you!

0

As the Connect class is being inherited by the Methods class, you can do it as follows using Parent which is a reference to the parent class in an inheritance relation:

parent::conectar();

How would it look:

public functionSegunda(){  
  $sql = mysqli_query(parent::conectar(), "MINHA QUERY");
}
  • Hello Yure. I tried to use the Parent, but it didn’t work, only works if I put the $connect->connect()

  • Unfortunately I can not uncouple or apply PDO, because I am, as I can say, putting out a fire... rs rs rs ...since the system already existed and this doubt I passed, is what I found wrong and I want to change, but I’m not getting it

  • Thank you to all the colleagues who were willing to help me. Hizer’s idea worked.

Browser other questions tagged

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