forked from AppStateESS/InternshipInventory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPdoFactory.php
69 lines (54 loc) · 1.63 KB
/
PdoFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
namespace Intern;
use \PDO;
/**
* Singleton Factory class for creating PDO objects based on
* PHPWS database configuration. Somewhat of a wrapper
* class for our current situation.
*
* @author jbooker
* @package homestead
*/
class PdoFactory {
static $factory;
private $pdo;
/**
* Returns a PdoFactory instance
* @return PdoFactory $pdo A PdoInstance object
*/
public static function getInstance()
{
if (!isset(self::$factory)) {
self::$factory = new PdoFactory();
}
return self::$factory;
}
/**
* Returns a PDO object which is connected to the current database
* @return $pdo A PDO instance, connected to the current DB
*/
public static function getPdoInstance()
{
$pdoFactory = self::getInstance();
return $pdoFactory->getPdo();
}
private function __construct()
{
if (!defined('PHPWS_DSN')) {
throw new Exception('Database connection DSN is not set.');
}
$dsnArray = \phpws2\Database::parseDSN(PHPWS_DSN);
$dsn = $this->createDsn($dsnArray['dbtype'], $dsnArray['dbhost'], $dsnArray['dbname']);
$this->pdo = new PDO($dsn, $dsnArray['dbuser'], $dsnArray['dbpass'], array(PDO::ATTR_PERSISTENT => true));
// Make sure PDO will throw exceptions on error
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function getPdo()
{
return $this->pdo;
}
private function createDsn($dbType, $host, $dbName)
{
return "$dbType:" . ($host != '' ? "host=$host" : '') . ";dbname=$dbName";
}
}