你調查過Unit of Work模式?
下面是您如何開始的一個非常粗暴的例子。
基本的UnitOfWork容器。
class UnitOfWork
{
protected $entities = array();
protected $completed = array();
final public function addEntity(IWorkUnitEntity $entity)
{
$this->entities[] = $entity;
}
final public function execute()
{
try {
foreach ($this->entities as $entity)
{
$entity->execute();
$completed[] = $entity;
}
}
catch (UnitOfWorkRollbackException $e)
{
$this->rollbackCompleted();
}
return $this->commitAll();
}
protected function rollbackCompleted()
{
while ($entity = array_pop($this->completed))
{
$entity->rollback();
}
}
protected function commitAll()
{
try {
foreach ($this->entities as $entity)
{
$entity->commit();
}
}
catch (UnitOfWorkRollbackException $e)
{
$this->rollbackCompleted();
return false;
}
return true;
}
}
幾個演員來幫助它一起
class UnitOfWorkRollbackException extends Exception {};
interface IWorkUnitEntity
{
public function execute();
public function rollback();
}
現在,一個工作實體
class FileMoverEntity implements IWorkUnitEntity
{
protected
$source
, $destination
, $newName
;
public function __construct($source, $destination, $newName = null)
{
$this->source = $source;
$this->destination = dirname($destination);
$this->newName = $newName;
}
public function execute()
{
if (is_readable($this->source) && is_writable($this->destination))
{
return true;
}
throw new UnitOfWorkRollbackException('File cannot be moved');
}
public function commit()
{
$filename = (null === $this->newName)
? basename($this->source)
: $this->newName
;
if (!rename($this->source, $this->destination . DIRECTORY_SEPARATOR . $filename))
{
throw new UnitOfWorkRollbackException('File move failed');
}
}
public function rollback()
{
// Nothing to do here since the file doesn't actually move until commit()
}
}
的例子全部放在一起。
$UoW = new UnitOfWork();
$UoW->addEntity(new FileMoverEntity('/tmp/foo', '/home/me', 'profile.jpg'));
$UoW->addEntity(new FileMoverEntity('/tmp/bar', '/root', 'profile.jpg'));
if ($UoW->execute())
{
// all operations successful
}
現在,我沒有這樣做,你會想在這裏有些東西 - 像跟蹤這些異常被拋出,這樣客戶端腳本可以訪問這些信息 - 但我認爲你的想法。當然,您可以繼續爲各種操作創建工作實體 - 數據庫更新,API調用,無論如何。
就連接到沒有事務安全表的數據庫而言 - 我沒有任何見解。
你所描述的正是交易的目的。我不明白「客戶支持」是什麼意思? – 2010-04-29 19:10:04
我的意思是我不知道我的軟件的用戶是否在他們的服務器上啓用了InnoDB。我需要假設它已關閉。 – Workoholic 2010-04-29 19:23:47