开发者

Why do we need the unset here?

Given the following example: (from Zend Quick Start Tutorial btw)

public function save(Application_Model_Guestbook $guestbook)
{
  $data = array(
    'email'   => $guestbook->getEmail(),
    'comment' => $guestbook->getComment(),
    'created' => date('Y-m-d H:i:s'),
  );

  if (null === ($id = $guestbook->getId())) {
     unset($data['id']);
     $this->getDbTable()->insert($data);
  } else {
     $this->getDbTable()->update($data, array('id = ?'开发者_JS百科 => $id));
  }
}

Why do we need the unset there ? I mean, why do we need to destroy a specific array key, if we haven't declare it before ? And even more bizarre, where do we declare it anyway?

We can have a look on getDbTable method, but even looking at it, I don't find an answer:

public function getDbTable()
{
    if (null === $this->_dbTable) {
        $this->setDbTable('Application_Model_DbTable_Guestbook');
    }
    return $this->_dbTable;
}

And if we look into the setDbTable method, there's no $data anywhere.

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

I know that Zend Framework will automatically find the id of our table here:

class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
    /** Table name */
    protected $_name    = 'guestbook';
}

But I don't understand if this is related somehow...

I believe I've put all the relevant information. Still, if there's nothing relevant, perhaps I'm missing something here: (source) http://framework.zend.com/manual/en/learning.quickstart.create-model.html

Thanks a lot


The code seems to imply that $data['id'] is always set, but it might have an empty value ('' or '0'). The unset is there to prevent the INSERT SQL query from trying to insert every new record with a fixed id of 0 (or to prevent the query from breaking due to invalid SQL syntax, can't tell with just this information) in this case.

Update: After reading it once more, it's obvious that the array $data cannot have its id member set at all (there's no code that might set it). Therefore that line is completely redundant the way the code is written right now. It might be a leftover from a previous version of the code.


Probably id is an autoincrement field. The unset is used to make sure, that the INSERT statement will not use a random id, but null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜