-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBase.php
97 lines (85 loc) · 2.11 KB
/
Base.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
<?php
require_once 'config.php';
class Base
{
private static $db;
private static $redis;
private $available = ['count_fib', 'count_prime'];
public function __construct()
{
$this->getDb();
$this->getRedis();
}
/**
* @return PDO
*/
public function getDb()
{
if (!self::$db) {
self::$db = new PDO(
'mysql:dbname='.DB_MYSQL_DATABASE.';host='.DB_MYSQL_HOST.':'.DB_MYSQL_PORT,
DB_MYSQL_USERNAME,
DB_MYSQL_PASSWORD
);
// $this->dbInit();
}
return self::$db;
}
/**
* @return \Redis
*/
public function getRedis()
{
if (self::$redis == null) {
try {
self::$redis = new \Redis();
self::$redis->connect(DB_REDIS_HOST, DB_REDIS_PORT) or die('Cannot connect Redis server!');
} catch (\Exception $e) {
die($e->getMessage());
}
}
return self::$redis;
}
/**
* @param string $value
*/
public function updateSum($value)
{
$records = 'SELECT `sum` FROM `test`';
$query = self::$db->prepare($records);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$newSum = bcadd($value, $result['sum']);
$sql = 'UPDATE `test` SET `sum` = ' . $newSum;
return $this->update($sql);
}
/**
* @param string $fieldName
* @param int $value
*/
public function updateCount($fieldName)
{
if (in_array($fieldName, $this->available)) {
$sql = 'UPDATE `test` SET `'.$fieldName.'` = `'.$fieldName.'` + 1';
return $this->update($sql);
} else {
exit('Unknown field name!');
}
}
/**
* Inits table values
*/
private function dbInit()
{
$sql = 'UPDATE `test` SET `sum` = 0, `count_fib` = 0, `count_prime` = 0';
return $this->update($sql);
}
/**
* @param string $sql
*/
private function update($sql)
{
$query = self::$db->prepare($sql);
return $query->execute();
}
}