【发布时间】:2011-11-22 17:14:07
【问题描述】:
在为我们的应用程序处理映射结构时,我们在代码一致性方面遇到了一些问题。虽然使用 Zend_Db_Select 类很容易进行选择查询(具有如下功能:$select->from('table')->where('id=?,1),但它不适用于更新/删除查询。那里不是像 Zend_Db_Update 或 Zend_Db_Delete 这样的类来构建更新和删除查询,就像构建选择一样。为了解决这个问题,我们扩展了 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);
}
}
使用这个类一切正常,但它让我们想知道我们是否可能遗漏了什么。有没有像 select 那样没有默认更新/删除类的原因,并且在其他地方使用这个类会给我们带来麻烦?
建议将不胜感激。 提前致谢,
伊利安人
【问题讨论】:
标签: php mapping zend-framework