在处理我们的应用程序的映射结构时,我们遇到了代码一致性问题。虽然使用Zend_Db_Select类很容易地进行选择查询(使用如下函数:$ select-> from('table') - > where('id = ?, 1),但它不适用于更新/删除查询。并不像Zend_Db_Update或Zend_Db_Delete那样构建更新和删除查询,就像构建select一样,为了解决这个问题,我们扩展了Zend_Db_Select类,如下代码所示:代码显示了扩展Zend_Db_Select类的自定义类在底部的一些小例子代码来显示如何使用它。Zend_Db_Select更新/删除查询
<?php
class Unica_Model_Statement extends Zend_Db_Select
{
public function __construct($oMapper)
{
parent::__construct($oMapper->getAdapter());
$this->from($oMapper->getTableName());
}
/**
* @desc Make a string that can be used for updates and delete
* From the string "SELECT `column` FROM `tabelnaam` WHERE `id` = 1" only the part "`id = `" is returned.
* @return string
*/
public function toAltString()
{
$sQuery = $this->assemble(); // Get the full query string
$sFrom = $this->_renderFrom(''); // Get the FROM part of the string
// Get the text after the FROM (and therefore not using the "SELECT `colname`" part)
$sString = strstr($sQuery,$sFrom);
// Delete the FROM itself from the query (therefore deleting the "FROM `tabelnaam`" part)
$sString = str_replace($sFrom, '', $sString);
// Delete the word "WHERE" from the string.
$sString = str_replace('WHERE', '', $sString);
return $sString;
}
}
################################################
# Below code is just to demonstrate the usage. #
################################################
class Default_IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$person = new Unica_Model_Person_Entity();
$statement = new Unica_Model_Statement($person->getMapper());
$statement->where('id = ?' , 1);
$person->getMapper()->delete($statement);
}
}
class Unica_Model_Person_Mapper
{
public function delete($statement)
{
$where = $statement->toAltString();
$this->getAdapter()->delete($this->_tableName,$where);
}
}
一切工作正常使用这个类,但是它让我们知道,如果我们也许失去了一些东西。是否有一个原因有没有默认的更新/删除类似的选择和将使用这个类给我们在其他地方的麻烦?
建议将不胜感激。 由于提前,
Ilians
感谢您的答复,你是正确的报价。我试图自动引用所有内容,以便程序员不必费尽心思地引用所有内容(即使他忘记了它也是安全的)。但是,myDelete函数将如何与where中的多个值一起工作?就像:“DELETE WHERE id = 3 OR adress ='test'AND language!='EN' – Ilians
根据WHERE子句的复杂程度,您需要或多或少地调整代码。只使用“AND”和场平等,只是为了展示一个简单的例子。 – dinopmi
我之前尝试过类似的方法,但是发现自己陷入了类似数组键的问题,就像 array( 'id'=> 3, 'ID'=> 4 ) 使用像这样虽然使比posibilities 阵列( 更大的 'ID =?'=> 3, 'ID =?'=> 4 ) – Ilians