@
@
@Twitt2018-04-09 12:56:10
PHP
@Twitt, 2018-04-09 12:56:10

How to bypass global in this situation?

there is a Database.php class, and there is a config.php file.
Actually, when in Database.php I do require(__DIR__ . '/config.php');
and I want to use a variable with config.php in construct, until I enter global $db_name; I won't be able to use them.
Because I know that globals are evil, and I want to keep the code clean from the beginning, I need to find a bypass for this case.
So, what is the workaround in this situation?
Now it looks like this

public function __construct()
    {
        try {
            global $config;
            $this->pdo = new PDO("mysql:host=localhost;dbname=" . $config['db_name'], $config['db_user'], $config['db_password']);
        } catch(Exception $e) {
            echo 'Sorry ' . $e->getMessage();
        }
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maksim Fedorov, 2018-04-09
_

If you have a goal, besides “make this code work” , there are other goals: to study and do it right ,
I advise you to look towards the introduction of a DI container, including for configs.
This is described in detail in Eliseev’s video, link to an excerpt:
PSR-7 framework 4/6: Dependency injection container
Or take a ready-made DI component (for example, from Symfony)

I
Ildar Saribzhanov, 2018-04-09
@Bluz

Pass connection parameters to constructor when instantiating

class Database
{
  public function __construct($db_name, $db_user, $db_password)
  {
    try {
      $this->pdo = new PDO("mysql:host=localhost;dbname=" . $db_name, $db_user, $db_password);
    } catch (Exception $e) {
      echo 'Sorry ' . $e->getMessage();
    }
  }
}


...........................

$db = new Database($config['db_name'], $config['db_user'], $config['db_password']);

And they say that try / catch in this case is bad manners, but this is not accurate

S
Sanovskiy, 2018-04-09
@Sanovskiy

The Global Repository pattern
is not needed. Extra parameters are not needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question