Single database instance

Asked

Viewed 264 times

2

I have a controller and need to access 2 or more tables from my database, ex:

 $userModel = loadModel('userModel');
   $userModel->setTable('users');
   $userModel->getAllUser();

   $outroModel = loadModel('outroModel');
   $outroModel->setTable('outros');
   $outroModel->getAllOutros();

Each being an object of this, classes that extend the Model, which connects to the database, Ex User:

class userModel extends Model {

    private $table;

    function __construct() {
        parent::__construct();
    }

    public function setTable($table) {
        $this -> table = $table;
    }

    public function getTable() {
        return $this -> table;
    }

    public function getAllUsers() {

        $this -> setSql("SELECT * FROM {$this->getTable()}");
        $getAll = $this -> getAll();
        return $getAll;

    }

Model:

abstract class Model {

    protected $db;
    protected $sql;

    function __construct() {

        $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);

        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME;
        try {
            $this -> db = new PDO($dsn, DB_USER, DB_PASS, $options);
            return $this -> db;

        } catch (exception $e) {
            echo $e -> getMessage();
        }

    }
....

In doing so, will I be opening more than one connection with the bank? If so, what is the best way to do this?

  • For an example of injection at this link: http://answall.com/a/16771/6026

2 answers

2


You end up creating two instances (or more) of the PDO class, in which case one would be sufficient for bank operations. There is a model and I will share, with Injection of Dependencies and layer DAL.

Interfaces

interface ConnectionInterface {
    public function Close();
    public function Connection();
}
interface ClienteInterface {
    public function setId($value);
    public function setNome($value);
    public function getId();
    public function getNome();
}
interface FornecedorInterface {
    public function setId($value);
    public function setRazaoSocial($value);
    public function getId();
    public function getRazaoSocial();
}

Implementing these Interfaces

class Connection implements ConnectionInterface {
    private $db;
    public function _construct(){
        $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
        $dsn = 'mysql:host=localhost;dbname=dbtest';
        $this->db = new PDO($dsn, 'root', 'senha', $options);
    }
    public function Close(){
        unset($this->db);
    }
    public function Connection(){
        return $this->db;
    }
}
class Cliente implements ClienteInterface {
    private $id;
    private $nome;
    public function __construct($id = 0, $nome = ''){
        $this->id = $id;
        $this->nome = $nome;
    }
    public function setId($value){
        $this->id = $value;
    }
    public function setNome($value){
        $this->nome = $value;
    }
    public function getId(){
        return $this->id;
    }
    public function getNome(){
        return $this->nome;
    }
}

class Fornecedor implements FornecedorInterface {
    private $id;
    private $razaoSocial;
    public function __construct($id = 0, $razaoSocial = ''){
        $this->id = $id;
        $this->razaoSocial = $razaoSocial;
    }
    public function setId($value){
        $this->id = $value;
    }
    public function setRazaoSocial($value){
        $this->razaoSocial = $value;
    }
    public function getId(){
        return $this->id;
    }
    public function getRazaoSocial(){
        return $this->razaoSocial;
    }
}

DAL

class DalCliente {
    private $Connection;
    public function _construct(ConnectionInterface $Connection){
        $this->Connection = $Connection;            
    }
    public function Insert(ClienteInterface $cliente){
        $sts = $this->Connection->prepare('INSERT INTO tbcliente(nome) values(?)');
        $sts->bindValue(1, $cliente->getNome(),PDO::PARAM_STR);
        $sts->execute();
        $cliente->setId($this->Connection->lastInsertId());         
        return $cliente;
    }
    public function Edit(ClienteInterface $cliente){
        $sts = $this->Connection->prepare('UPDATE tbcliente SET nome=? WHERE id=?');
        $sts->bindValue(1, $cliente->getNome(),PDO::PARAM_STR);
        $sts->bindValue(2, $cliente->getId(),PDO::PARAM_INT);
        $sts->execute();
    }
}

class DalFornecedor {
    private $Connection;
    public function _construct(ConnectionInterface $Connection){
        $this->Connection = $Connection;            
    }
    public function Insert(FornecedorInterface $fornecedor){
        $sts = $this->Connection->prepare('INSERT INTO tbfornecedor(nome) values(?)');
        $sts->bindValue(1, $fornecedor->getRazaoSocial(),PDO::PARAM_STR);
        $sts->execute();
        $cliente->setId($this->Connection->lastInsertId());         
        return $fornecedor;
    }
    public function Edit(FornecedorInterface $fornecedor){
        $sts = $this->Connection->prepare('UPDATE tbfornecedor SET razaosocial=? WHERE id=?');
        $sts->bindValue(1, $fornecedor->getRazaoSocial(),PDO::PARAM_STR);
        $sts->bindValue(2, $fornecedor->getId(),PDO::PARAM_INT);
        $sts->execute();
    }
}

How to use

Let’s say that you in a code block, or in a controller have to open two different DAL SQL, do:

$connection    = new Connection();
$dalcliente    = new DalCliente($connection);
$dalfornecedor = new DalFornecedor($connection);

Insert operation

$fornecedor = new Fornecedor(0, "Fornecedor 1");
$fornecedor = $dalfornecedor->Insert($fornecedor); // inserindo fornecedor

Right now you are injecting a Class that is responsible for connection with bank in two other classes, eliminating the duplication of instances, improving performance, standardizing its software to facilitate new implementations and corrections.

Folder organization inserir a descrição da imagem aqui

Folder Connection: Connection.php

DAL folder: DalCliente.php and DalFornecedor.php

Folder Interfaces: ConnectionInterface.php, ClienteInterface.php and FornecedorInterface.php

Pasta Poco: Cliente.php and Fornecedor.php

To call !!!

Create the files at the root and include what you need:

include 'Interfaces/ConnectionInterface.php';
include 'Connection/Connection.php';

include 'Interfaces/ClienteInterface.php';
include 'Interfaces/FornecedorInterface.php';
include 'Poco/Cliente.php';
include 'Poco/Fornecedor.php';

include 'Dal/DalCliente.php';
include 'Dal/DalFornecedor.php';
  • I understand, in which case the first two codes would be the file "Model"? and I would no longer make a file for each model, eg: Suppliedormodel,userModel, would just be a DAL call? I got confused a little with the organization rs

  • Yes, I understood this part that you used only one connection object, I was confused with the part of "responsibility" kk, I learned this way, the model would make the connection with the BD and tbm some generic methods and each "class" would extend it and the "implement"[...]

  • Got it, it really gets cleaner in my view, one more thing, you created an interface Fonercador , for example, soon after implemented it and DAL implemented again? that part is really necessary?

  • Okay, if possible also make an example of the organization of the files ( yes, I’m asking you this) kkk, thank you so much so far, is helping me a lot!

  • Just one more thing, I still don’t know how to organize it in files and call them in the right way...

Show 1 more comment

0

Just include the Finally and close the connection within this.

  • I didn’t understand, how would that be?

  • Finally is another block, optional, to be used in conjunction with Try...catch(). Every routine coded within one Finally shall be implemented independently if the Try was successfully executed or if any catch captured some exception. However, the Finally was added only in PHP 5.5 and, at least in Brazil, using it can still restrict the application to specific servers and suddenly "force" the programmer to opt for an international.

Browser other questions tagged

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