【发布时间】:2011-07-29 20:45:40
【问题描述】:
谁能告诉我如何确定查询类型,即在通过 MySQL 执行之前选择、更新、删除或插入。
我坚信 Zend Framework 内部可能正在使用 mysql*_query 函数来执行它们。
我需要一个集中式函数,它会在执行前返回查询类型。
我为每个数据库表使用三个文件
我给你举个例子。
假设我想为类别表创建模型。
所以我将创建以下文件
DbTable/Categories.php
class Application_Model_DbTable_Categories extends Zend_Db_Table_Abstract {
protected $_name = 'categories';
protected $_dependentTables = array('Application_Model_DbTable_Videos');
}
Categories.php
class Application_Model_Categories extends Application_Model_CommonGetterSetter {
protected $_type = array('id' => 'int', 'name' => 'string', 'slug' => 'string', 'status' => 'int');
public function __construct(array $options = null) {
parent::__construct($options, __CLASS__);
}
}
CategoriesMapper.php
class Application_Model_CategoriesMapper {
protected $_dbTable;
public function setDbTable($dbTable) {
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getDbTable() {
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Categories');
}
return $this->_dbTable;
}
public function save(Application_Model_Categories $categories) {
$data = array(
'name' => $categories->name,
'slug' => $categories->slug,
'status' => $categories->status,
);
if (@$categories->id <= 0) {
return $this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $categories->id));
return $categories->id;
}
}
CommonGetterSetter.php
class Application_Model_CommonGetterSetter {
protected $_data = array();
private $_class_name;
public function __construct(array $options = null, $class_name = null) {
if (is_array($options)) {
foreach ($options as $key => $value) {
$this->$key = $value;
}
$this->_class_name = $class_name;
}
}
public function __set($name, $value) {
if (!array_key_exists($name, $this->_type)) {
throw new Exception("Invalid {$this->_class_name} property". $name);
}
else {
settype($value, $this->_type[$name]);
$this->_data[$name] = $value;
}
}
public function __get($name) {
if (!array_key_exists($name, $this->_type)) {
throw new Exception("Invalid {$this->_class_name} property". $name);
}
else {
return $this->_data[$name];
}
}
}
所以我想知道执行了哪个查询,我应该在哪里写什么?
非常感谢。
我知道代码有点长,但这是为了给出一个完整的想法。
【问题讨论】:
-
你不应该坚信,你应该阅读代码!
标签: php zend-framework