简体   繁体   中英

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 = ?' => $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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM