|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ubiquity\orm\traits; |
|
4
|
|
|
|
|
5
|
|
|
use Ubiquity\controllers\Startup; |
|
6
|
|
|
use Ubiquity\exceptions\DAOException; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Ubiquity\orm\traits$DAOPooling |
|
10
|
|
|
* This class is part of Ubiquity |
|
11
|
|
|
* |
|
12
|
|
|
* @author jcheron <[email protected]> |
|
13
|
|
|
* @version 1.0.0 |
|
14
|
|
|
* |
|
15
|
|
|
* @property array $db |
|
16
|
|
|
* |
|
17
|
|
|
*/ |
|
18
|
|
|
trait DAOPooling { |
|
19
|
|
|
|
|
20
|
|
|
abstract public static function startDatabase(&$config, $offset = null); |
|
21
|
|
|
|
|
22
|
|
|
abstract public static function getDbOffset(&$config, $offset = null); |
|
23
|
|
|
protected static $pool; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Initialize pooling (To invoke during Swoole startup) |
|
27
|
|
|
* |
|
28
|
|
|
* @param array $config |
|
29
|
|
|
* @param ?string $offset |
|
30
|
|
|
*/ |
|
31
|
|
|
public static function initPooling(&$config, $offset = null) { |
|
32
|
|
|
$dbConfig = self::getDbOffset ( $config, $offset ); |
|
33
|
|
|
$wrapperClass = $dbConfig ['wrapper'] ?? \Ubiquity\db\providers\pdo\PDOWrapper::class; |
|
34
|
|
|
if (\method_exists ( $wrapperClass, 'getPoolClass' )) { |
|
35
|
|
|
$poolClass = \call_user_func ( $wrapperClass . '::getPoolClass' ); |
|
36
|
|
|
if (\class_exists ( $poolClass, true )) { |
|
37
|
|
|
self::$pool = new $poolClass ( $config, $offset ); |
|
38
|
|
|
} else { |
|
39
|
|
|
throw new DAOException ( $poolClass . ' class does not exists!' ); |
|
40
|
|
|
} |
|
41
|
|
|
} else { |
|
42
|
|
|
throw new DAOException ( $wrapperClass . ' does not support connection pooling!' ); |
|
43
|
|
|
} |
|
44
|
|
|
self::startDatabase ( $config, $offset ); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* gets a new DbConnection from pool |
|
49
|
|
|
* |
|
50
|
|
|
* @param string $offset |
|
51
|
|
|
* @return mixed |
|
52
|
|
|
*/ |
|
53
|
|
|
public static function pool($offset = 'default') { |
|
54
|
|
|
if (! isset ( self::$db [$offset] )) { |
|
55
|
|
|
self::startDatabase ( Startup::$config, $offset ); |
|
56
|
|
|
} |
|
57
|
|
|
return self::$db [$offset]->pool (); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public static function freePool($db) { |
|
61
|
|
|
self::$pool->put ( $db ); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
public static function go($asyncCallable, $offset = 'default') { |
|
65
|
|
|
$vars = \get_defined_vars (); |
|
66
|
|
|
\Swoole\Coroutine::create ( function () use ($vars, $asyncCallable, $offset) { |
|
67
|
|
|
$db = self::pool ( $offset ); |
|
68
|
|
|
\call_user_func_array ( $asyncCallable, $vars ); |
|
69
|
|
|
self::freePool ( $db ); |
|
70
|
|
|
} ); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
|