在哪里添加 3 个函数以及如何编写 findByUsername - Zend Framework



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

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

如果我想添加以下功能:

  1. 函数 does用户名存在已经($username) {返回布尔值}
  2. function findByUsername($username) {return a $user}
  3. 函数激活用户($user) {只需激活一个$user}

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

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

@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;
    }

至于您的最后一个问题,您可以通过获取行然后仅保存开关来真正简单地激活 A 记录,我认为您设置了某种类型的标志或布尔值来激活记录。这个可能需要进入具体的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.
        }
    }

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

最新更新