Sometime, we want to display random items. May be, we want to display new item on the top or other ideas. It will be more efficient if we made a helper class. It will centralize the data function. In this tutorial, we will try to build helper class to replace code in last tutorial.
Create a file named "helper.php" within joomla/modules/mod_hello. Enter following code:
<?php
defined('_JEXEC') or die('Restricted access');
class modHelloHelper
{
function getHello($params)
{
$items = $params->get('items', 1);
$db =& JFactory::getDBO();
$result = null;
$query = 'SELECT id, message'
.' FROM #__hello'
.' WHERE published = 1'
;
$db->setQuery($query, 0, $items);
$rows = $db->loadObjectList();
if ($db->getErrorNum()) {
JError::raiseWarning( 500, $db->stderr(true) );
}
return $rows;
}
function renderHello(&$hello, &$params)
{
$link = JRoute::_('index.php?option=com_hello&id='.$hello->id.'&task=view');
return $link;
}
}
?>
Now, it is time to change your "mod_hello.php" within joomla/modules/mod_hello.php. Change with following code:
<?php
defined('_JEXEC') or die('Restricted access');
require(dirname(__FILE__).DS.'helper.php');
$rows = modHelloHelper::getHello($params);
foreach($rows as $row)
{
echo 'ID: <A href="'. modHelloHelper::renderHello($row, $params)
.'">'.$row->id.'</A> </br>';
echo $row->message .'</br>';
}
?>
Can you catch the idea?