Began to deal with OOP php, namely the MVC architecture. There was a question about connecting to the database. In one of the lessons on this topic, in the model in the functions interacting with the database, the function of creating a PDO object is called, that is, with several actions with the database on one page, several several PDO objects are created. It seems to me it is not right. And it is better to create one connection and use it before executing the whole code. But how and in what place to call this connection? Create a front controller or router? - but not every page needs a connection to the database. It was thought to check the existence of the created connection and if it is not there to create it, but there were problems with the visibility of a variable from the functions of one model in the functions of another. In general, how to do it right?
1 answer
Most likely you are faced with the Singleton pattern - the creation of a single instance of the database class. Such an object is not created every time, only once. And then when referring to the class, the presence of the object is checked and if it is created - given away, a new one is not created. In the case of a database, it is used very often.
class Singleton{ private static $instance = null; private static $i = 0; /** * @return Singleton */ public static function getInstance(){ if (null === self::$instance){ self::$instance = new self(); } return self::$instance; } private function __wakeup(){} private function __clone(){} private function __construct(){} } $obj = Singleton::getInstance(); |