【发布时间】:2011-06-23 05:32:18
【问题描述】:
考虑以下几点:
/** (Cas_Template_Tree::DeleteNode)
* Deletes the given node from the tree, and all of it's children.
*
* @static
* @throws Exception
* @param Cas_Template_Node $node
* @return void
*/
public static function DeleteNode(Cas_Template_Node $node)
{
$table = new Cas_Table_Templates();
$adapter = $table->getAdapter();
$leftStr = $adapter->quoteIdentifier('Left');
$rightStr = $adapter->quoteIdentifier('Right');
try
{
$adapter->beginTransaction();
$row = $table->find($node->GetId())->current();
$dependantRowSelector = array(
"$leftStr >= ?" => $row->Left,
"$rightStr <= ?" => $row->Right
);
//Get the rows removed so that we can nuke the ACLs later.
$rowsToDelete = $table->fetchAll($dependantRowSelector)->toArray();
//Delete the rows.
$table->delete($dependantRowSelector);
//Delete access control lists on those rows.
foreach ($rowsToDelete as $rowToDelete)
{
Cas_Acl::CreateExisting($rowToDelete['Acl'])->Delete();
}
$left = (int)$row->Left;
$right = (int)$row->Right;
$difference = $right - $left + 1;
$table->update(array('Left' => new Zend_Db_Expr("$leftStr - $difference")),
array("$leftStr > ?" => $right));
$table->update(array('Right' => new Zend_Db_Expr("$rightStr - $difference")),
array("$rightStr > ?" => $right));
$adapter->commit();
}
catch (Exception $ex)
{
$adapter->rollBack();
throw $ex;
}
}
/** (Cas_Acl::Delete)
* Removes this ACL (and all of its dependent access control entries) from the database.
* @return void
*/
public function Delete()
{
$aclTable = new Cas_Table_AccessControlLists();
$aceTable = new Cas_Table_AccessControlEntries();
$adapter = Zend_Db_Table_Abstract::getDefaultAdapter();
$identifierName = $adapter->quoteIdentifier('Identifier');
$aclName = $adapter->quoteIdentifier('Acl');
try
{
$adapter->beginTransaction();
$aceTable->delete(array("$aclName = ?" => $this->GetId()));
$aclTable->delete(array("$identifierName = ?" => $this->GetId()));
}
catch (Exception $ex)
{
$adapter->rollBack();
throw $ex;
}
}
注意这两个都要求事务如何工作,否则操作将不是原子的(这会很糟糕;))但是,这里有两个事务块。原始的 DeleteNode 方法调用Cas_Acl::Delete(),它也尝试在事务块内执行自身。理想情况下,Zend_Db 会足够聪明地识别这种情况,并且对于这个特定的调用忽略 Cas_Acl::Delete 中的开始事务和提交/回滚调用。
上面的代码安全吗?能否以任何方式显着改善?
【问题讨论】:
-
你有时会直接打电话给
Delete()吗?还是只在DeleteNode()内调用? -
@singles:是的——只要需要删除 ACL,就会调用
Cas_Acl::Delete。该应用程序管理的大多数对象都附加了一个 ACL。其中一些对象使用事务,而另一些则不需要。 -
你的代码提出了一个问题,就像黑线鳕的胡须在 tintin omg.wthax.org/haddock.jpg 的床单上或下,我认为“$adapter->beginTransaction();”应该设置在“try {} catch”之前而不是里面
标签: php zend-framework