Add a Model to Joomla Site Part

The HtmlView class asks the model for data using the get method. For example, this get method converts the get('Item') call into a getItem() call on the model, which is the method which you have to provide in the model.

The model files are stored in the /src/Model folder. This is similar to the backend where you need to extend the model class with one of the available models.

Since the Planet View will display information about the single item, this class will extend the ItemModel. In the class, you must define getItem() method.

Step 1: Model File

site/src/Model/PlanetModel.php

use Joomla\CMS\MVC\Model\ItemModel;

class PlanetModel extends ItemModel
{
    public function getItem($pk = null)
    {  
      if ($pk == null)
      {
          $pk = Factory::getApplication()->input->getInt('id');
      }
       
        $db = $this->getDatabase();
        $query = $db->getQuery(true);
       
        $query->select('*')
            ->from($db->quoteName('#__planets', 'a'))
            ->where(array(
                        $db->quoteName('a.id') . ' = ' . $db->quote($pk),
                        $db->quoteName('a.published') . ' = 1',
                        )
                    );
 
        $db->setQuery($query);
 
        $item = $db->loadObject();
 
      return $item;
    }
}

Testing Component at Frontend

You can check by visiting the frontend Url:

index.php?option=com_stars&view=planet&id=5

Replace the Id with any valid id record in the database table. You should see the title of the Planet.

In the next tutorial, we will add a menu type to the site part so that instead of vising by the direct url, you can create menu item for the same.