I have multiple classes and most of them need to connect to database,
How can I set PDO options/host/dbname etc only once and then use it in every class while having the following in mind:
- I don't want to wrap PDO
- I need to close the PDO connection after each query (
$db=null
), so I simply cannot just use$db = new PDO(...)
and then pass$db
to my classes
I want to skip having this in every class that needs to connect to the database:
<?php
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}