1

如 Zend 文档中所述,我有一个 User.php 模型、DbTable/User.php 模型和 UserMapper.php 文件。

映射器有 fetchAll()、find($id)、getDbTable()、save() 和 setDbTable()

如果我想添加以下功能:

  1. 函数 doesUsernameExistAlready($username) {返回一个布尔值}
  2. 函数 findByUsername($username) {返回一个 $user}
  3. function activateUser($user) {只需激活一个 $user}

要遵循 Zend 的最佳实践,应该在哪里添加这 3 个函数?应该将它们添加到 UserMapper.php 还是 User.php?还是它们属于控制器(UserController)?

对于 findByUsername,我如何编写一个函数来搜索我的用户表中的用户名?在我的例子中,用户名是电子邮件地址并且是唯一的(在 MySQL 中定义)。

4

1 回答 1

3

@drew010 像往常一样是正确的,把这些函数放在你的映射器中。老实说,这些可能都可以放在抽象或基本映射器中,因此您的所有映射器都可以使用该功能。

您可以轻松地在映射器中创建一个函数 recordExists() 并将表和列作为参数传递:

  //you can either pass in the table name or have it be a property
  public function recordExists($table = null, $column) {
      //The table syntax may change depending on the scope
        $table = $this->_tableName;
        $exists = new Zend_Validate_Db_RecordExists(array(
        'table' => $table,
        'field' => $column
        )):

    return $exists;
    }

对于 findBy() 方法,我喜欢将 3 个变量传递给该方法,然后使用 fetchAll() 返回一个对象数组。这样,如果列返回一行或五十行,我以相同的方式处理输出。

    /**
     * findByColumn() returns an array of rows selected
     * by column name and column value.
     * Optional orderBy value, pass $order as string ie 'id ASC'.
     *
     * @param string $column
     * @param string $value
     * @param string $order
     * @return array returns an array of objects
     */
public function findByColumn($column, $value, $order = NULL) {
        $select = $this->_getGateway()->select();
        $select->where("$column = ?", $value);
        if (!is_null($order)) {
            $select->order($order);
        }
        $result = $this->_getGateway()->fetchAll($select);
        $entities = array();
        foreach ($result as $row) {
            //create objects
            $entity = $this->createEntity($row);
            $entities[] = $entity;
        }
        return $entities;
    }

至于你的最后一个问题,你可以通过获取行然后只保存开关来激活 aa 记录,我认为你设置了某种类型的标志或布尔值来激活记录。这可能需要进入具体的 UserMapper,因为我发现使用我用来保存记录的方法,基本的 save() 方法并不总是有效。

 //you'll set the activate switch when the user object is instantiated
    public function activate(Application_Model_User $user) {
        if (!is_null($user->id)) {
            $select = $this->_getGateway()->select();
            $select->where('id = ?', $user->id);
            $row = $this->_getGateway()->fetchRow($select);
            $row->activate = $user->activate;
            //This is the cool thing about save(), you can change as many or few columns as you need.
           $row->save()
        return $row;  
        } else {
           //handle error, as we only want to be able to change an existing user.
        }

    }

这可能比您需要的更多,但我希望它有所帮助。

于 2012-06-18T03:51:48.087 回答