swoole-framwork/core/init/MyDB.php
2024-05-21 14:33:56 +08:00

126 lines
3.4 KiB
PHP

<?php
namespace Core\init;
use Core\annotations\Bean;
use Core\BeanFactory;
use Core\lib\PDOPool;
use Illuminate\Database\Capsule\Manager as lvDB;
/**
* @Bean()
* @package Core\init
* @method \Illuminate\Database\Query\Builder table(string $table,string|null $as=null,string|null $connection=null)
*/
class MyDB
{
private $lvDB;
private $dbSource='default';
private $transctionDB = false;
/**
* @var PDOPool
*/
public $pdopool;
public function __construct($db_obj = false)
{
global $GLOBAL_CONFIGS;
if (isset($GLOBAL_CONFIGS['db'])) {
$this->lvDB = new LvDb();
$configs = $GLOBAL_CONFIGS['db'];
foreach ($configs as $key => $config){
$this->lvDB->addConnection($config,$key);
}
$this->lvDB->addConnection(["driver"=>"mysql"], $key);
//设置全局静态访问
$this->lvDB->setAsGlobal();
//启动Eloquent
$this->lvDB->bootEloquent();
}
$this->transctionDB = $db_obj;
$this->pdopool = BeanFactory::getBean(PDOPool::class);
if ($db_obj) {
$this->lvDB->getConnection($this->dbSource)->setPdo($this->transctionDB->db);
$this->lvDB->getConnection($this->dbSource)->beginTransaction();
}
}
public function __call($methodName, $arguments)
{
try{
if ($this->transctionDB) {//事务对象
$pdo_object = $this->transctionDB;
$isTranstion = true;
}else{
$isTranstion = false;
$pdo_object = $this->pdopool->getConnection();
$this->lvDB->getConnection($this->dbSource)->setPdo($pdo_object->db);//设置pdo对象
}
if ($methodName == 'model') {
return $arguments[0];
}
$ret = $this->lvDB::connection($this->dbSource)->$methodName(...$arguments);
return $ret;
}catch (\Exception $exception){
return null;
}finally{
if($pdo_object && ! $isTranstion){
$this->pdopool->close($pdo_object); //放回连接
}
}
//return $ret;
//用。。。解构数组
//return $this->lvDB::$methodName(...$arguments);
}
public function setDbSource($dbSource)
{
$this->dbSource = $dbSource;
}
public function getDbSource()
{
return $this->dbSource;
}
/**
* 开启事务
*/
public function Begin()
{
return new self($this->pdopool->getConnection());
}
/**
* 提交事务
*/
public function Commit()
{
try{
$this->lvDB->getConnection($this->dbSource)->commit();
}
finally{
if ($this->transctionDB) {
$this->pdopool->close($this->transctionDB);
$this->transctionDB = false;
}
}
}
/**
* 事务回滚
*/
public function RollBack()
{
try{
$this->lvDB->getConnection($this->dbSource)->rollBack();
}catch (\Exception $exception) {
return $exception->getMessage();
}
finally{
if ($this->transctionDB) {
$this->pdopool->close($this->transctionDB);
$this->transctionDB = false;
}
}
}
}