WillRy /
rabbitrun
| 1 | <?php |
||
| 2 | |||
| 3 | namespace WillRy\RabbitRun\Connections; |
||
| 4 | |||
| 5 | /** |
||
| 6 | * Class Connect Singleton Pattern |
||
| 7 | */ |
||
| 8 | class ConnectPDO |
||
| 9 | { |
||
| 10 | /** @var array */ |
||
| 11 | private static $opt = []; |
||
| 12 | |||
| 13 | /** @var \PDO */ |
||
| 14 | private static $instance; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * Connect constructor. Private singleton |
||
| 18 | */ |
||
| 19 | private function __construct() |
||
| 20 | { |
||
| 21 | } |
||
| 22 | |||
| 23 | /** |
||
| 24 | * Connect clone. Private singleton |
||
| 25 | */ |
||
| 26 | private function __clone() |
||
| 27 | { |
||
| 28 | } |
||
| 29 | |||
| 30 | public static function getInstance($forceNew = false) |
||
| 31 | { |
||
| 32 | if (empty(self::$instance) || $forceNew) { |
||
| 33 | try { |
||
| 34 | $driver = self::$opt["driver"]; |
||
| 35 | $host = self::$opt["host"]; |
||
| 36 | $dbname = self::$opt["dbname"]; |
||
| 37 | $dbuser = self::$opt["user"]; |
||
| 38 | $dbpass = self::$opt["pass"]; |
||
| 39 | $port = self::$opt["port"]; |
||
| 40 | |||
| 41 | $conn = new \PDO("$driver:host=$host;dbname=$dbname;port=$port", $dbuser, $dbpass); |
||
| 42 | $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); |
||
| 43 | $conn->setAttribute(\PDO::ATTR_STRINGIFY_FETCHES, false); |
||
| 44 | $conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); |
||
| 45 | |||
| 46 | self::$instance = $conn; |
||
| 47 | } catch (\Exception $exception) { |
||
| 48 | die('Connection error PDO' . $exception->getMessage()); |
||
|
0 ignored issues
–
show
|
|||
| 49 | } |
||
| 50 | } |
||
| 51 | |||
| 52 | return self::$instance; |
||
| 53 | } |
||
| 54 | |||
| 55 | public static function config($driver, $host, $dbname, $user, $pass, $port) |
||
| 56 | { |
||
| 57 | self::$opt = [ |
||
| 58 | 'driver' => $driver, |
||
| 59 | 'host' => $host, |
||
| 60 | 'dbname' => $dbname, |
||
| 61 | 'user' => $user, |
||
| 62 | 'pass' => $pass, |
||
| 63 | 'port' => $port |
||
| 64 | ]; |
||
| 65 | |||
| 66 | return ConnectPDO::getInstance(); |
||
| 67 | } |
||
| 68 | } |
||
| 69 |
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.