SQL实现:
abstract class SQL
{
abstract public function connect();
abstract public function query($sql);
abstract public function queryAndReturn($sql);
abstract public function startTransaction();
abstract public function commit();
abstract public function rollback();
}
class MySQL extends SQL
{
public function connect()
{
mysql_connect (....)
}
public function query($sql)
{
return mysql_query($sql);
}
public function queryAndReturn()
{
$result = $this->query($sql);
$results = [];
whilte ($item = mysql_fetch_assoc($result))
{
$results[] = $item;
}
return $results;
}
public function startTransaction()
{
return $this->query('START TRANSACTION');
}
public function commit()
{
return $this->query('COMMIT');
}
public function rollback()
{
return $this->query('ROLLBACK');
}
public function runAtomicFunction (\Closure $function)
{
try
{
$this->query('SET autocommit=0');
$this->startTransaction();
$function();
$this->commit();
}
catch (Exception $e)
{
$this->rollback();
}
}
}
最后4种方法类似于"交易"所以让我们把它们移到另一个类:
class MySQL extends SQL
{
public function connect()
{
mysql_connect (....)
}
public function query($sql)
{
return mysql_query($sql);
}
public function queryAndReturn()
{
$result = $this->query($sql);
$results = [];
whilte ($item = mysql_fetch_assoc($result))
{
$results[] = $item;
}
return $results;
}
public function getNewTransaction()
{
return new Transaction($this);
}
}
class Transaction
{
private $db;
public function __construct(Sql $db)
{
$this->db = $db;
}
public function startTransaction()
{
return $this->db->query('START TRANSACTION');
}
public function commit()
{
return $this->db->query('COMMIT');
}
public function rollback()
{
return $this->db->query('ROLLBACK');
}
public function runAtomicFunction (\Closure $function)
{
try
{
$this->db->query('SET autocommit=0');
$this->db->startTransaction();
$function();
$this->db->commit();
}
catch (Exception $e)
{
$this->db->rollback();
}
}
}
$sql = new MySQL();
$t = $sql->getNewTransaction();
$t->runAtomicFunction(...);
这一切都很好,但这是循环引用进入的时候。 Sql
取决于Transaction
,反之亦然。这是否表明我不能将交易分开?
答案 0 :(得分:1)
如果我不能消除循环引用,那么它们应该属于一个类?
将它们拆分有什么好处?
我会将他们留在一个班级,除非你能提出一个很好的理由将他们分开。