Hi, community. Another question. I understand that much has been set forth, but I do not find an answer for myself. Singleton would not like, because of his denial and "anti-usefulness") Suppose there are X models in the controller. Inheritance as it comes from Model. I want to make it easier to do initialization in the parent, so that later I donβt add a bunch of parameters in the descendants.
UPD: Changed so that you can connect to multiple database servers
<?php class Database { private static $_instance; private $current_base; public function __construct() { } /** * @param string $parameter * @return \mysqli */ public function connect($parameter = 'default') { if (empty(self::$_instance[$parameter])) { if (!$this->current_base) { $this->setConnect($parameter); } $database = new \mysqli($this->current_base['server'], $this->current_base['user'], $this->current_base['password'], $this->current_base['database'], $this->current_base['port']); if ($database->connect_error) { die('ΠΡΠΈΠ±ΠΊΠ° ΠΏΠΎΠ΄ΠΊΠ»ΡΡΠ΅Π½ΠΈΡ (' . $database->connect_errno . ') ' . $database->connect_error); } $database->set_charset("utf8"); self::$_instance[$parameter] = $database; } return self::$_instance[$parameter]; } public function setConnect($name) { // $database_config['default'] = [...] // Π’ΡΡ ΠΊΡΡΠ°ΡΠΈ, ΠΏΡΠΈ ΠΎΠ±ΡΡΠΎΡΡΠ΅Π»ΡΡΡΠ²Π°Ρ
Π²ΡΠ»Π΅ΡΠ°Π΅Ρ Π½ΠΎΡΠΈΡ, ΡΠΈΠΏΠ° Π½Π΅ Π²ΠΈΠ΄ΠΈΡ ΠΎΠ½ ΠΌΠ°ΡΡΠΈΠ² Π² db.php require_once APPPATH . 'config/db.php'; if (is_array($database_config[$name])) { $this->current_base = $database_config[$name]; } else { $this->current_base = $database_config['default']; } } } // Π Model public function __construct() { if (!session_id()) { session_start(); } $database = new Database(); $this->db = $database->connect('default'); // Π’Π΅ΠΏΠ΅ΡΡ ΠΊΠ°ΠΊ Π±Ρ ΡΠΌΠ΅Π½ΠΈΡΡ ΠΈ/ΠΈΠ»ΠΈ Π±Π°Π·Ρ Π΄Π°Π½Π½ΡΡ
(Π² ΡΠΌΡΡΠ»Π΅ DATABASE()) // ΠΠ°ΠΊ Π½ΠΈΠΆΠ΅ Π½Π΅ Π²ΡΡ
ΠΎΠ΄ΠΈΡ, Π² DAtabase $_instance Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅ΡΡΡ //$database->setConnect('other'); //$this->db2 = $database->connect('other'); }