1616 * You can obtain one at https://mozilla.org/MPL/2.0/.
1717 * @license MPL-2.0 https://mozilla.org/MPL/2.0/
1818 * @source https://github.com/wdes/simple-php-model-system
19+ * @version 1.1.0
1920 */
2021
2122/**
@@ -30,20 +31,54 @@ class Database
3031 private $ dbConfig ;
3132
3233 /**
33- * @var PDO
34+ * @var PDO|null
3435 */
3536 private $ connection ;
3637
37- /** @var self|null $instance */
38- protected static $ instance = null ;
38+ /** @var self[] $instances */
39+ protected static $ instances = [] ;
3940
40- public function __construct (array $ config )
41+ public const MAIN_CONNECTION = 0x1 ;
42+ public const SECOND_CONNECTION = 0x2 ;
43+ public const THIRD_CONNECTION = 0x2 ;
44+
45+ /**
46+ * Build a Database object
47+ *
48+ * @param array $config
49+ * @param int $connection Database::MAIN_CONNECTION, Database::SECOND_CONNECTION, Database::THIRD_CONNECTION
50+ */
51+ public function __construct (array $ config , int $ connection = self ::MAIN_CONNECTION )
4152 {
42- $ this ->dbConfig = $ config ['database ' ][$ config ['currentDatabaseEnv ' ]];
43- self ::$ instance = $ this ;
53+ if (! isset ($ config ['database ' ]) || ! isset ($ config ['currentDatabaseEnv ' ])) {
54+ throw new Exception ('Invalid config to create the Database ' );
55+ }
56+
57+ $ this ->dbConfig = $ config ['database ' ][$ config ['currentDatabaseEnv ' ]];
58+ self ::$ instances [$ connection ] = $ this ;
4459 }
4560
4661 /**
62+ * @since 1.1.0
63+ */
64+ public function disconnect (): void
65+ {
66+ if ($ this ->connection !== null ) {
67+ $ this ->connection = null ;
68+ }
69+ }
70+
71+ /**
72+ * @since 1.1.0
73+ */
74+ public function __destruct ()
75+ {
76+ $ this ->disconnect ();
77+ }
78+
79+ /**
80+ * Connect to the database
81+ *
4782 * @throws PDOException when the connetion fails
4883 */
4984 public function connect (): void
@@ -79,13 +114,23 @@ public function getConnection(): PDO
79114 return $ this ->connection ;
80115 }
81116
82- public static function getInstance (): self
117+ /**
118+ * Access the database instance
119+ *
120+ * @param int $connection Database::MAIN_CONNECTION, Database::SECOND_CONNECTION, Database::THIRD_CONNECTION
121+ */
122+ public static function getInstance (int $ connection = self ::MAIN_CONNECTION ): self
83123 {
84- if (self ::$ instance === null ) {
85- throw new Exception ('The Database object was never created, use new Database() at least once ' );
124+ if ((self ::$ instances [$ connection ] ?? null ) === null ) {
125+ throw new Exception (
126+ sprintf (
127+ 'The Database object was never created (connection: %d), use new Database() at least once ' ,
128+ $ connection
129+ )
130+ );
86131 }
87132
88- return self ::$ instance ;
133+ return self ::$ instances [ $ connection ] ;
89134 }
90135
91136 /**
0 commit comments