1 | <?php |
||
32 | trait Handler |
||
33 | { |
||
34 | /** @} */ |
||
35 | |||
36 | /** PDO connection to the database. */ |
||
37 | public $pdo; |
||
38 | |||
39 | /** |
||
40 | * \addtogroup Bot Bot |
||
41 | * @{ |
||
42 | */ |
||
43 | |||
44 | /** |
||
45 | * \brief Open a database connection using PDO. |
||
46 | * \details Provides a simple way to initialize a database connection |
||
47 | * and create a PDO instance. |
||
48 | * @param array $params Parameters for initialize connection. |
||
49 | * Index required: |
||
50 | * - <code>username</code> |
||
51 | * - <code>password</code> (can be a null string) |
||
52 | * Optional index: |
||
53 | * - <code>adapter</code> <b>Default</b>: <code>mysql</code> |
||
54 | * - <code>host</code> <b>Default</b>: <code>localhost</code> |
||
55 | * - <code>options</code> (<i>Array of options passed when creating PDO object</i>) |
||
56 | * @return bool True when the connection is succefully created. |
||
57 | */ |
||
58 | 1 | public function connect(array $params) : bool |
|
59 | { |
||
60 | 1 | $params = $this->addDefaultValue($params); |
|
61 | 1 | $config = $this->getDns($params); |
|
62 | |||
63 | try { |
||
64 | 1 | $this->pdo = new \PDO($config, $params['username'], $params['password'], $params['options']); |
|
65 | 1 | $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); |
|
66 | |||
67 | 1 | return true; |
|
68 | } catch (\PDOException $e) { |
||
69 | echo 'Unable to connect to database, an error occured:' . $e->getMessage(); |
||
70 | } |
||
71 | |||
72 | return false; |
||
73 | } |
||
74 | |||
75 | /** \brief (<i>Internal</i>) Add default connection value to parameter passed to PDO. |
||
76 | * @param array $params Parameter for PDO connection. |
||
77 | * @return array Parameter with defaults value. |
||
78 | */ |
||
79 | 2 | protected function addDefaultValue(array $params) : array |
|
84 | |||
85 | /** \brief (<i>Internal</i>) Returns a string that can passed to PDO as DNS parameter in order to open connection. |
||
86 | * @param array $params Array containing parameter of the connection |
||
87 | * @return string Parameters contained in array $params sanitized in a string that can be passed as DNS param of PDO object creation. |
||
88 | */ |
||
89 | 3 | protected function getDns($params) : string |
|
111 | |||
112 | /** @} */ |
||
113 | } |
||
114 |