我有100多张桌子。我需要访问每个表,具体取决于表单上提供的用户名。用户名是表名。我不想为表示表的每一个创建100个类。有没有办法可以做到这一点?
答案 0 :(得分:0)
我在我的基本映射器类中使用与此类似的代码:
protected $_tableGateway = NULL;
protected $_tableName = NULL;
public function __construct(Zend_Db_Table_Abstract $tableGateway = NULL, $tableName = NULL) {
//set the tablename in a concrete mapper, set it here in constructor or create mutator to setTableName.
if (!is_null($tableName)) {
$this->_tableName = $tableName;
}
if (is_null($tableGateway)) {
$this->_tableGateway = new Zend_Db_Table($this->_tableName);
} else {
$this->_tableGateway = $tableGateway;
}
}
这样的事情应该允许你传入Zend_Db_Table_Abstract(DbTable模型)的实例或作为表名的字符串。
//controller code
$username = $form->getValue('username');
$mapper = My_Mapper(NULL, $username);
$result = $mapper->fetchAll();
我认为这并没有真正完成,但应该有助于显示方式。
如果您没有使用地图制作工具并且只想使用DbTable模型,您可以尝试(这可以传递给接受Zend_Db_Table_Abstract的映射器):
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
function __construct(array $config) {
parent::__construct($config);
}
}
并在你的控制器/动作中使用它:
/**
* Supported params for $config are:
* - db = user-supplied instance of database connector,
* or key name of registry instance.
* - name = table name.
* - primary = string or array of primary key(s).
* - rowClass = row class name.
* - rowsetClass = rowset class name.
* - referenceMap = array structure to declare relationship
* to parent tables.
* - dependentTables = array of child tables.
* - metadataCache = cache for information from adapter describeTable().
*/
$username = $form->getValue('username');
$config = array('name'=> $username, 'primary' => 'id');
$model = new Application_Model_DbTable_Users($config);//This should setup your table
$result = $model->fetchAll(); //perform queries or execute methods defined in DbTable model
或者您可以在控制器/操作中使用Zend_Db_Table:
$username = $form->getValue('username');
$db = new Zend_Db_Table($username);
$result = $db->fetchAll();
祝你好运......