Search code examples
joomlajoomla2.5

Adding in a hit counter to Joomla


I'm creating a custom component for Joomla 2.5. I want to add in a hit counter for the detailed view (like on Joomla content etc.)

So I've done some research and found the JTable::hit function which I'm assuming is what I need (Joomla docs page here). However I'm highly unclear as to where I need to implement this. Is it in the model somewhere when I retrieve the row from the database - or is it somewhere in the view? Advise would be much appreciated!


Solution

  • If you have a look at how they did it in Joomla, you will see that they implemented the functionality in the model, and call the method from the view.

    For example, article.php model has

    public function hit($pk = 0)
    {
            $hitcount = JRequest::getInt('hitcount', 1);
    
            if ($hitcount)
            {
                // Initialise variables.
                $pk = (!empty($pk)) ? $pk : (int) $this->getState('article.id');
                $db = $this->getDbo();
    
                $db->setQuery(
                        'UPDATE #__content' .
                        ' SET hits = hits + 1' .
                        ' WHERE id = '.(int) $pk
                );
    
                if (!$db->query()) {
                        $this->setError($db->getErrorMsg());
                        return false;
                }
            }
    
            return true;
    }
    

    and

    view.html.php has

    $model = $this->getModel();
    $model->hit();