Back to Table class

Method hit

public bool
hit
(mixed $pk = null)
Method to increment the hits for a row if the necessary property/field exists.
Parameters
  • mixed $pk An optional primary key value to increment. If not set the instance property value is used.
Returns
  • bool True on success.
Since
  • 1.7.0
-
  • \UnexpectedValueException
Class: Table
Project: Joomla

Method hit - Source code

/**
 * Method to increment the hits for a row if the necessary property/field exists.
 *
 * @param   mixed  $pk  An optional primary key value to increment. If not set the instance property value is used.
 *
 * @return  boolean  True on success.
 *
 * @since   1.7.0
 * @throws  \UnexpectedValueException
 */
public function hit($pk = null)
{
    // Pre-processing by observers
    $event = AbstractEvent::create('onTableBeforeHit', ['subject' => $this, 'pk' => $pk]);
    $this->getDispatcher()->dispatch('onTableBeforeHit', $event);
    // If there is no hits field, just return true.
    if (!$this->hasField('hits')) {
        return true;
    }
    if (\is_null($pk)) {
        $pk = array();
        foreach ($this->_tbl_keys as $key) {
            $pk[$key] = $this->{$key};
        }
    } elseif (!\is_array($pk)) {
        $pk = array($this->_tbl_key => $pk);
    }
    foreach ($this->_tbl_keys as $key) {
        $pk[$key] = \is_null($pk[$key]) ? $this->{$key} : $pk[$key];
        if ($pk[$key] === null) {
            throw new \UnexpectedValueException('Null primary key not allowed.');
        }
    }
    // Get column name.
    $hitsField = $this->getColumnAlias('hits');
    // Check the row in by primary key.
    $query = $this->_db->getQuery(true)->update($this->_tbl)->set($this->_db->quoteName($hitsField) . ' = (' . $this->_db->quoteName($hitsField) . ' + 1)');
    $this->appendPrimaryKeys($query, $pk);
    $this->_db->setQuery($query);
    $this->_db->execute();
    // Set table values in the object.
    $this->hits++;
    // Pre-processing by observers
    $event = AbstractEvent::create('onTableAfterHit', ['subject' => $this, 'pk' => $pk]);
    $this->getDispatcher()->dispatch('onTableAfterHit', $event);
    return true;
}