How to insert the connection inside the functions without repeating the instructions?

Asked

Viewed 70 times

1

Since I have several functions that will use this connection, how to enter the $pdo within the function without copying the require and $pdo within each of the functions that I will draw up?

require("classes/Database.php");
$pdo  = Database::connect();

function inserir (){

}
function listar (){

}
function atualizar (){

}

function excluir(){

  if ($_GET['tipo'] == 'blog' && $_GET['funcao'] == 'excluir'){

    $pdo->query("DELETE FROM tb_blog WHERE ID = " . $_GET['id'] . "");
    echo "
      <META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>
      <script type=\"text/javascript\">
        window.location = \"index\";
      </script>
      ";
    return;
  }

}
excluirDados();
  • May pass $pdo as a function argument ... $_GET should also be global or external variables should not be injected directly like this. Another option is to create a class for sharing $pdo among the methods.

  • ... pass as argument to the function ... can you show me that?

2 answers

3


May pass $pdo as an argument for functions or to create a class to share the connection between methods. Do not inject global or external variables into a function because they can break the behavior of the function which is a reusable piece of code.

function novo ($pdo, $registro){

}
function listar ($pdo){

}
function atualizar ($pdo, $registro){

}

function excluir($pdo, $id){

    $stmt = $pdo->prepare("DELETE FROM tb_blog WHERE ID = ?");
    if(!$stmt->execute(array($id))){
       print_r($stmt->errorInfo());
    }
    echo "
      <META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>
      <script type=\"text/javascript\">
        window.location = \"index\";
      </script>
      ";
    return;
  }

}


 if (!empty($_GET['tipo']) && $_GET['tipo'] == 'blog' && !empty($_GET['funcao']) && $_GET['funcao'] == 'excluir'){
    $id = !empty($_GET['id']) && ctype_digit($_GET['id'] ? $_GET['id'] : 0;
    excluir($pdo, $id);
}

Class approach, did not repeat the validation with $_GET but she still needed, use the function header() to redirect the user does not make sense to use javascript for this

class blogDAO{
    private $connection;

    function __construct(PDO $pdo){
        $this->connection = $pdo;
    }

    function novo($registro){

    }
    function listar(){

    }
    function atualizar ($pdo, $registro){

    }

    function excluir($id){

        $stmt = $this->connection->prepare("DELETE FROM tb_blog WHERE ID = ?");
        if(!$stmt->execute(array($id))){
            print_r($stmt->errorInfo());
            return false;
        }else{
            return true;
        }
    }

}

$daoBlog = new blogDAO(Database::connect());

if($_GET ...){
    if($daoBlog->excluir($id)){
        header('Location: index.php');
    }else{
        echo 'erro ...';
    }
}
  • I’m having trouble making the list ... list(); It is giving error in my code when I call the function this way. Can demonstrate in the own answer pf.

  • rray muitooooo thanks for your reply but I’m still walking the paths of the POO, I already understand a lot that is there but I still have difficulty using ALL THIS. For now a solution with the functions will solve, but surely in the future I will use your class.

  • Function list() all the time Fatal error: Call to a Member Function query() on a non-object on line 12 >>> foreach ($Pdo->query($sql) as $line) { ?>

  • @Marcosvinicius seems to connect $pdo is not valid.

  • @Marcosvinicius places the code of the list and its call. It should not be extended.

2

The idea of @rray to pass PDO as argument really is excellent.

Only as a complement, it is possible to induce the type of the parameter so that the PDO.

Example:

function excluir(\PDO $pdo, $id) {
    $pdo->query(/*...*/);
}

In that case, if something other than the instance of a PDO, a fatal error will be generated.

This can make your code more readable to other programmers ;)

Example:

$pdo = new PDO(/* Dados para conexão **/);

excluir($pdo, 5);

Or else:

$ob = new MinhaClasse

$ob->excluir($pdo, 5);

Browser other questions tagged

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