How to instantiate $ pdo = connect () without repeating?

4

For example I have a class named user :

class User
{
    public $nome;
    private $email;
    protected $senha;

    public function __construct(){

    }

    public function insert($email, $senha){
        require_once "conexao.php";
        $pdo = conectar();

        $insertSQL = $pdo->prepare('INSERT INTO tbl (valores) VALUES (?)');
        $insertSQL->bindValue(1, $this->lalala(), PDO::PARAM_STR);
        $insertSQL->execute();
    }

and also see that I need to make require ():

require_once "conexao.php";
$pdo = connect();

But I have to do these two lines every time for every method of the class. There is no way to create a single time and be available throughout the class scope, type the attributes?

I've tried it as an attribute and it did not work. With the builder it also was not (maybe I did it wrong).

    
asked by anonymous 21.07.2017 / 20:44

2 answers

6

One suggestion is to create a property and connection in your class and pass the connection to it via constructor. So whenever the object (of User ) needs a connection it will already be open.

class User
{
    public $nome;
    private $email;
    protected $senha;
    private $db; //propriedade da conexão

    //pega a conexão externa e joga dentro da propriedade
    public function __construct($db){
       $this->db = $db;
    }

    public function insert($email, $senha){
       $insertSQL = $this->db->prepare('INSERT INTO tbl (valores) VALUES (?)');
       //demais códigos ...
}

At the time of calling do

include 'conexao.php'; 
$user = new User($pdo);

//ou ainda:
$user = new User(conectar());

There is little advantage to creating a function only to create and return the PDO connection with the user parameters and direct password in the code, in which case you can pass the direct connection variable.

    
21.07.2017 / 20:59
-2

You can do this:

require_once "conexao.php";

class User
{
    public $nome;
    private $email;
    protected $senha;

    public function __construct(){

    }

    public function insert($email, $senha){
        $pdo = conectar();

        $insertSQL = $pdo->prepare('INSERT INTO tbl (valores) VALUES (?)');
        $insertSQL->bindValue(1, $this->lalala(), PDO::PARAM_STR);
        $insertSQL->execute();
    }
    
21.07.2017 / 20:59