-
Notifications
You must be signed in to change notification settings - Fork 1
/
PDOBuilder.php
128 lines (106 loc) · 2.38 KB
/
PDOBuilder.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
namespace phputil;
/**
* PDO Builder.
*
* @author Thiago Delgado Pinto
*
* @see http://www.php.net/manual/en/pdo.connections.php
* @see http://php.net/manual/en/pdo.setattribute.php
* @see http://php.net/manual/en/pdo.constants.php
*
* Example on how to use it:
*
* <?php
* require_once 'vendor/autoload.php';
* use \phputil\PDOBuilder;
*
* $pdo = PDOBuilder::with()
* ->dsn( 'mysql:dbname=mydb;host=127.0.0.1;' )
* ->username( 'myuser' )
* ->password( 'mypass' )
* ->modeException()
* ->persistent()
* ->mySqlUTF8()
* ->build();
* ?>
*
*/
class PDOBuilder {
private $dsn = '';
private $username = '';
private $password = '';
private $options = array();
private $modeException = false;
static function with() {
return new PDOBuilder();
}
/**
* Build the PDO. This is the last method in the sequence you should call.
*
* @return \PDO
* @throws \PDOException
*/
function build() {
$pdo = new \PDO( $this->dsn, $this->username, $this->password, $this->options );
if ( $this->modeException ) {
$pdo->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
}
return $pdo;
}
// Basic data
function dsn( $dsn ) {
$this->dsn = $dsn;
return $this;
}
function username( $username ) {
$this->username = $username;
return $this;
}
function password( $password ) {
$this->password = $password;
return $this;
}
function options( $options ) {
$this->options = is_array( $options ) ? $options : array();
return $this;
}
// Mode Exception
function modeException( $b = true ) {
$this->modeException = $b;
return $this;
}
function inModeException() {
return $this->modeException( true );
}
function notInModeException() {
return $this->modeException( false );
}
// Persistent
function persistence( $b = true ) {
$this->ensureOptionsIsArray();
$this->options[ \PDO::ATTR_PERSISTENT ] = $b;
return $this;
}
function persistent() {
return $this->persistence( true );
}
function notPersistent() {
return $this->persistence( false );
}
// MySQL
function mySqlUTF8() {
$this->ensureOptionsIsArray();
$this->options[ \PDO::MYSQL_ATTR_INIT_COMMAND ] = 'SET NAMES utf8';
return $this;
}
//
// PRIVATE
//
private function ensureOptionsIsArray() {
if ( ! is_array( $this->options ) ) {
$this->options = array();
}
}
}
?>