I have a config folder which contains the db.php file, which contains the following code:

<?php $host = 'localhost'; $dbname = 'test'; $charset = 'utf8'; $dbuser = 'root'; $dbpassword = ''; $opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); $dsn = "mysql:host = $host; dbname = $dbname; charset = $charset"; $pdo = new PDO($dsn, $dbuser, $dbpassword, $opt); 

Then I have a folder with models: models which contains the file WorkersModel.php with the following code:

 <?php function getAllWorkers() { $stmt = $pdo->query('SELECT * FROM `workers`'); while($row = $stmt->fetch()) { echo $row['name']; } } 

The problem is that I cannot access the $ pdo variable from this function, or rather, I can, but only if I declare $ pdo global inside the function:

 <?php function getAllWorkers() { global $pdo; ... 

This model connects the controller from the controllers folder and calls the functions of the model in its functions.

All these folders: models , config , controllers are on the same level. At the same level is the www folder, which in turn is index.php , which "calls" the controllers, connects files from the config folder and contains the following code:

 <?php require_once '../config/config.php'; require_once '../libs/Functions.php'; require_once '../config/db.php'; $controllerName = isset($_GET['controller']) ? ucfirst($_GET['controller']) : 'Index'; $actionName = isset($_GET['action']) ? $_GET['action'] : 'index'; loadPage($twig, $controllerName, $actionName); 

In the Functions.php file, I have all sorts of common functions, such as page loading and template loading.

So: how do I properly initialize the PDO and connect it to the model?

    2 answers 2

    For the solution of your task, I think, the Singleton pattern is not a bad fit. Using this pattern, you can create an object that will be available throughout the application. They say, however, that now singleton was written to antipatterns, but in your case, its use should be a good decision.

    1. In the db.php file you place the class to connect to the database:

       <?php class DB { private static $instance; // экземпляр объекта /** * * @var PDO */ private $pdo = false; /* Защищаем от создания через new DB */ private function __construct() { } /* Защищаем от создания через клонирование */ private function __clone() { } /* Защищаем от создания через unserialize */ private function __wakeup() { } /** * Возвращает единственный экземпляр класса * @return DB */ public static function getInstance() { if (empty(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * Подключаемся к БД * @param type $dsn * @param type $dbuser * @param type $dbpassword * @param type $opt * @throws Exception */ public function connect($dsn, $dbuser, $dbpassword, $opt) { try { $this->pdo = new PDO($dsn, $dbuser, $dbpassword, $opt); } catch (Exception $e) { throw $e; } } /** * Получить ссылку на PDO * @return boolean */ public function get_pdo() { if ($this->pdo instanceof PDO) { return $this->pdo; } return false; } /** * Закрываем соединение с БД */ public function close() { $this->pdo = null; } } /** * Параметры для подключения к БД */ $host = 'localhost'; $dbname = 'test'; $charset = 'utf8'; $dbuser = 'root'; $dbpassword = ''; $opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); $dsn = "mysql:host = {$host}; dbname = {$dbname}; charset = {$charset}"; /** * ******************************* */ /** * Попытка подключени к БД */ try { DB::getInstance()->connect($dsn, $dbuser, $dbpassword, $opt); } catch (Exception $e) { echo $e->getMessage(); exit; } /** * ******************************* */ 
    2. In the index.php file after calling load_page :

       DB::getInstance()->close(); 
    3. And now you can access the PDO in all model files, like this:

    WorkersModel.php

     <?php function getAllWorkers() { $pdo = DB::getInstance()->get_pdo(); $stmt = $pdo->query('SELECT * FROM `workers`'); while($row = $stmt->fetch()) { echo $row['name']; } } 

    Perhaps I am mistaken, but, according to the given code examples, it seems to me that you are not very well familiar with the OOP paradigm. If this is true, then I strongly recommend that you thoroughly take up the study of this paradigm.

    • You're right. I began to study OOP only recently, thanks for the answer and for an illustrative example. - Flaffen

    Since this is not about classes, but about functions, I think that here you just need to forget all the beautiful words about models and controllers , honestly call your approach a procedural blender, and not sweat about using global - this approach is the perfect solution.

    • Thank. Although I would still better start using OOP ... Or try :) - Flaffen