Recover instantiated object in another file in PHP

Asked

Viewed 176 times

0

Quick question: how to recover the instance of an object created in a different file in a PHP application?

Full question: I am creating a project for PHP studies where I have the file conn.php which contains the PDO instance for the database connection. Another file called functions.php contains the function getAllUsers() that should perform the query in the database and return the results.

Using only the require('conn/conn.php') would not recover the instance of the object created in the file? If not, how could it achieve this?

Thank you in advance for all your attention!

The code of the archives conn.php and functions.php follow below:

Conn.php

<?php

/*
** Arquivo de conexão com o banco de dados
** Quaisquer alterão irá impactar na aplicação inteira
*/

require('config.php');

// Função de conexão com o banco de dados
function databaseStartConnection() {

    $dsn = DBBRAND . ":dbname=" . DBNAME . ";host=" . DBHOST;

    // Tente se conectar ao banco com as crendenciais fornecidas
    try {
        $pdo = new PDO($dsn, DBUSER, DBPASS);

    } catch (PDOException $e) {

        // Em caso de erro, exiba a mensagem e encerre a aplicação
        echo "<p><b>Erro de conexão com o banco de dados: </b>" . $e->getMessage() . "</p><br>";
        die();
    }   
}

functions.php

<?php

/* 
** Realiza consulta teste
** Modificar este arquivo para a consulta real
*/

require('conn/conn.php');

// Inicia conexão com o banco de dados
databaseStartConnection();

// Recupera do banco todos os usuários
function getAllUsers($pdo = $this->$pdo) { // Recuperar o objeto criado no arquivo conn.php

    // Consulta vai aqui

}

// Fecha conexão com o banco de dados
databaseCloseConnection();
  • 3

    PHP OO is rarely a good thing. PHP is almost always used in situations where there is no state preservation, and OO is directly linked to state maintenance. It has a way of serializing and deserializing objects, but it’s usually even worse. However, in your given example, you have no reason to use any OO. Even though unfortunately something forces you to use PDO, reconnecting to each script is what is normally done. And the fact of using OO syntax does not prevent thinking procedurally.

  • Got it. But anyway I would like to keep my query functions in the bank within the file functions.php and my connection within the conn.php. I cannot think at this point another viable way to do this. Doing everything within the same file would be very disorganized.

  • Yes, it’s convenient to keep it that way, but note that this has nothing to do with needing the first instance created. The fact that you use a "new" does not mean that you should cling to that instance. Each time something includes that script, an instance will be created and discarded at the end.

  • Right, within my function getAllUsers() I would not need to have established the connection with my bank, with the credentials passed inside my file conn.php? Or would I need to create a new connection for each function I create? I don’t think that would be very practical.

  • 1

    Very calm at this time kkkk. Note that we are not talking about OO anymore. The normal PHP when used in quick scripts (web pages) is to open the connection 1 time only at the beginning of the script, store in a variable, and use during the life of the script. If it will be in the script itself or if it will be included at the beginning, it is a matter of code organization. Usually a require_once is made at the beginning for this. Again, this is independent of the paradigm you’re going to use. Be a $var = new PDO(...); or $var = mysqli_connect(...); the idea is the same, do 1x at the beginning and use the variable during the script.

  • The fact that it is an object instance or pointer to a connection is detail, considering the very short life time of the script.

  • @Bacco I managed to solve using a return in my variable $pdo and recovering the instance in the file functions.php assigning to a new variable the value of this return. I will edit my question with the new code if you want to take a look. The problem is that now I can’t call the function getAllUsers() in my view without having to pass a parameter.. I will think about how I will resolve this yet, but thank you very much for your attention.

Show 2 more comments

1 answer

0

I was able to solve by creating a Return within my function databaseStartConnection() and recovering its value within the mo my file functions.php, as can be seen in the following code.

Function databaseStartConnection() within the Conn.php file

function databaseStartConnection() {

    $dsn = DBBRAND . ":dbname=" . DBNAME . ";host=" . DBHOST;
    $dbUser = DBUSER;
    $dbPass = DBPASS;

    // Tente se conectar ao banco com as crendenciais fornecidas
    try {
        $conn = new PDO($dsn, $dbUser, $dbPass);
        return $conn;

    } catch (PDOException $e) {

        // Em caso de erro, exiba a mensagem e encerre a aplicação
        echo "<p><b>Erro de conexão com o banco de dados: </b>" . $e->getMessage() . "</p><br>";
        die();
    }   
}

Function getAllUsers() inside the archive functions.php receiving $Conn as parameter

$conn = databaseStartConnection();

// Recupera do banco todos os usuários
function getAllUsers($conn) { 

    if(isset($conn)) {
        $v = "TRUE";
    } else {
        $v = "FALSE";
    }

    return $v;
}

echo getAllUsers($conn);

Browser response

TRUE

  • 2

    Just out of curiosity, remember that you do not need to be in a Function the connection code, then the variable will be available in the main scope. Additionally, PHP has to force the use of global variables within functions, but I sincerely recommend avoiding, it is rarely the correct solution. I won’t say you can never use it (up to pq if you are purist at this point, you shouldn’t even use PHP anymore) but it is a habit that usually ends up generating a headache, especially when the project increases.

Browser other questions tagged

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