0

我有100多张桌子。我需要根据表单上提供的用户名访问这些表中的每一个。用户名是表名。我不想为每个代表一个表的类创建 100 个类。有没有办法我可以做到这一点?

4

1 回答 1

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();

祝你好运...

于 2012-06-23T11:29:47.907 回答