Module Development in Joomla

Exclusive offer: get 50% off this eBook here
Learning Joomla! 1.5 Extension Development: Creating Modules, Components, and Plugins with PHP

Learning Joomla! 1.5 Extension Development: Creating Modules, Components, and Plugins with PHP — Save 50%

A practical tutorial for creating your first Joomla! 1.5 extensions with PHP

$23.99    $12.00
by Joseph L. LeBlanc | July 2008 | Joomla! MySQL Content Management Open Source PHP

Modules in Joomla can always help us to add special functionality or special features to our website. In this article by Joseph LeBlanc, we will see how to create and configure a basic module and centralize data access and output using helper classes. We will also have a look at how to select different display options using layouts.

Introduction

Modules in Joomla can be used to fetch and display data almost anywhere on a page in a website.In this article, we will cover the following topics on module development.

  • Registering the module in the database
  • Getting and setting parameters
  • Centralizing data access and output using helper classes
  • Selecting display options using layouts
  • Displaying the latest reviews
  • Displaying a random review

We will assume that we have a table in our database called jos_modules with the following fields title, ordering, position, published, module, showtitle, and params. We will also assume that we have a website that reviews different restaurants. However, visitors have to go to the component to see the reviews. We would be developing a module so that we could pull the content directly from the reviews and display them.

Registering the Module in the Database

As with the component, we will have to register the module in the database so that it can be referenced in the back end and used effectively. Entering a record into the jos_modules table will take care of this. Open your database console and enter the following query:

INSERT INTO jos_modules (title, ordering,
position, published, module, showtitle, params)
VALUES ('Restaurant Reviews', 1, 'left', 1,
'mod_reviews', 1, 'style=simplenitems=3nrandom=1');

If you're using phpMyAdmin, enter the fields as in the following screen:

Module Development in Joomla

If you refresh the front end right after entering the record in jos_modules, you'll notice that the module doesn't appear, even though the published column is set to 1. To fix this, go to Extensions | Module Manager in the back end and click the Restaurants Reviews link. Under Menu Assignment, select All and click Save.

Module Development in Joomla

In the front end, the left-hand side of your front page should look similar to the following:

Module Development in Joomla

Creating and Configuring a Basic Module

Modules are both simple and flexible. You can create a module that simply outputs static text or one that queries remote databases for things like weather reports. Although you can create rather complex modules, they're best suited for displaying data and simple forms. You will not typically use a module for complex record or session management; you can do this through a component or plug-in instead.

To create the module for our reviews, we will have to create a directory mod_reviews under /modules. We will also need to create the mod_reviews.php file inside mod_reviews. To start, we'll create a basic module that displays links to the most recent reviews. In the mod_reviews.php file, add the following code:

<?php
defined('_JEXEC') or die('Restricted access');
$items = $params->get('items', 1);
$db =& JFactory::getDBO();
$query = "SELECT id, name FROM #__reviews WHERE
published = '1' ORDER BY review_date DESC";
$db->setQuery( $query, 0, $items );
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo '<a href="' . JRoute::_('index.php?option=com_reviews&id='
. $row->id . '&task=view') . '">' . $row->name .
'</a><br />';
}
?>

When you save the file and refresh the homepage, your module should look similar to the following:

Module Development in Joomla

When the module is loaded, the $params object is pulled into scope and can be used to get and set the parameters. When we added the row into jos_modules, the params column contained three values: one for items (set to 3), one for style (set to simple), and another for random (set to 1). We set $items to the parameter items using the get() member function, defaulting to 1 if no value exists.

If desired, you can use the member function set($name, $value) to override or add a parameter for your module.

After getting a database object reference, we write a query to select the id and name form jos_reviews and order reverse chronologically by the published date. We use the second and third parameters of setQuery() to generate a LIMIT clause that is automatically added to the query. This ensures that the correct syntax is used for the database type. Once the query is built, we load all the relevant database rows, go through them, and provide a link to each review.


Learning Joomla! 1.5 Extension Development: Creating Modules, Components, and Plugins with PHP A practical tutorial for creating your first Joomla! 1.5 extensions with PHP
Published: June 2007
eBook Price: $23.99
Book Price: $34.99
See more
Select your format and quantity:

Recruiting Some Helpers

We would like to have our module do more than display links to the reviews. It would be helpful to include a summary of the review along with each link or have the opportunity to display a review at random. However, the way we have it coded currently is not sufficient to handle different scenarios efficiently. To fix this, we will centralize the data functions into a helper class. Create the helper.php file in /modules/mod_reviews and add the following code:

<?php
defined('_JEXEC') or die('Restricted access');
class modReviewsHelper
{
function getReviews(&$params)
{
$items = $params->get('items', 1);
$db =& JFactory::getDBO();
$query = "SELECT id, name, quicktake FROM #__reviews
WHERE published = '1' ORDER BY review_date DESC";
$db->setQuery( $query, 0, $items );
$rows = $db->loadObjectList();
return $rows;
}
function renderReview(&$review, &$params)
{
$link = JRoute::_
("index.php?option=com_reviews&task=view&id=" .
$review->id);
require(JModuleHelper::getLayoutPath
('mod_reviews', '_review'));
}
}
?>

The function getReviews() performs the same database actions as the original module, except that it returns the rows instead of going through them. This way, we separate the database functionality from the display logic. The quicktake column has been added to the query to gather the content necessary for longer review display formats.

We're going to use renderReview() to output single reviews. To create the link to a review, we pass index.php?option=com_reviews&task=view&id= and the review id into Jroute::_() to make our links search engine friendly. Finally, we use require() and the getLayoutPath() member function of JModuleHelper to include the _review template we're about to create.

Try Some Different Layouts

The helper class does not produce any output itself. Instead, renderReview() formats the link and then calls the getLayoutPath() member function in JModuleHelper to include a layout file named _review.

To create this file, make the folder tmpl under /modules/mod_reviews, create _review.php inside tmpl, and then add the following line of code:

<?php defined('_JEXEC') or die('Restricted access'); ?>
<a href="<?php echo $link ?>"><?php echo $review->name; ?></a><br />

The underscore at the beginning of _review is a convention to remind us that the layout is for internal use; it is not offered as a choice to the admin. In addition to this internal layout, we can create other layouts as different display options. To start, we will create one named default. Add the default.php file in /modules/mod_reviews/tmpl and add the following code:

<?php
defined('_JEXEC') or die('Restricted access');
foreach ($list as $review){
modReviewsHelper::renderReview($review, $params);
}
?>

Notice that this layout cycles through a list of reviews, calling the helper class function that prepares single reviews for display, which in turn loads in the _review layout. Using the same method, we will also create a bulleted layout. Create the bulleted.php file in /modules/mod_reviews/tmpl and add the following code to create the links as a bulleted list:

<?php defined('_JEXEC') or die('Restricted access'); ?>
<ul>
<?php
foreach ($list as $review)
{
echo "<li>";
modReviewsHelper::renderReview($review, $params);
echo "</li>";
}
?>
</ul>

The bulleted layout uses the same basic logic as the default layout; the only difference is that it wraps the results in bullets. Both options ultimately load the _review layout via the helper function, ensuring that the link formatting is consistent across layouts.

We now have two different display options and a helper class, but none of this code is yet accessible by the module. Open mod_reviews.php and replace the contents with the following code:

<?php
defined('_JEXEC') or die('Restricted access');
require(dirname(__FILE__).DS.'helper.php');
$list = modReviewsHelper::getReviews($params);
require(JModuleHelper::getLayoutPath('mod_reviews'));
?>

The first require() call pulls in the file for the helper class we just wrote. Next, we pull in a sorted set of recent reviews. Finally, we use getLayoutPath() to pull in a display layout. When no second parameter is specified for getLayoutPath(), default is assumed.

Save all the open files and refresh the front page in your browser. The module should look the same as in the last screenshot. Now, go back to mod_reviews.php and edit the call to getLayoutPath() so that the bulleted layout is called instead of default:

require(JModuleHelper::getLayoutPath('mod_reviews', 'bulleted'));

Save all the files and refresh your browser. The module should now appear similar to the following:

Module Development in Joomla

It would be nice if we could display a small portion of the review along with each link. Go back to /modules/mod_reviews/tmpl/_review.php and add the following highlighted code:

<a href="<?php echo $link ?>"><?php echo $review->name;
?></a><br />
<p>"<?php echo $review->quicktake ?>"</p><br />

Refresh your browser. If you entered something in the Quicktake field in the back end when editing your reviews, you should see something like the following:

Module Development in Joomla

Go back to mod_reviews.php and set the second parameter of getLayoutPath() to default. After saving the file and refreshing the browser, you should see the same reviews and quotes as before, only without the bullets. While the layout is changing, the output from _review is staying constant.

Module Development in Joomla

Mixing it Up

Our module is great at highlighting the latest opinions of our diners, but our frequent visitors may want the past reviews. Let's fix that with some adjustments to the module. Replace the line in mod_reviews.php where the $list function is set with the highlighted code:

<?php
defined('_JEXEC') or die('Restricted access');
require(dirname(__FILE__).DS.'helper.php');
$random = $params->get('random', 0);
if($random)
{
$list = modReviewsHelper::getRandomReview();
}
else
{
$list = modReviewsHelper::getReviews($params);
}
require(JModuleHelper::getLayoutPath
('mod_reviews', 'default'));
?>

Instead of simply pulling all the reviews, we now populate $list based on the module's parameters. The $params object is automatically placed into a global scope, pre-loaded with the settings for our module. We use the get() member function to pull the random parameter into $random, defaulting to 0 when there is no value. Next, we test the value of $random. If it is non-zero, the getRandomReview() member function is called, which we will be adding to modReviewsHelper in a moment. Otherwise, we get the reviews as we did before.

Now that the parameter checking code is in place, open helper.php and add the following function to the modReviewsHelper class:

function getRandomReview()
{
$db =& JFactory::getDBO();
$query = "SELECT id, name, quicktake FROM #__reviews";
$db->setQuery( $query );
$rows = $db->loadObjectList();
$i = rand(0, count($rows) - 1 );
$row = array( $rows[$i] );
return $row;
}

The function first gets a reference to the current database connection. The query is set to load the id, name, and quicktake columns from all rows in the jos_reviews table. After all the rows have been loaded into $rows, PHP's rand() function is used to get a random value between 0 and the number of rows less one, inclusive. The variable $row is then set to an array containing one element: the object found at the randomly selected index of $rows. It is necessary to wrap $rows[$i] in an array as our output code is expecting one.

Save the file and refresh your browser. Then refresh it repeatedly. With any luck, single reviews should appear at random.

Module Development in Joomla

Summary

Now that this module is in place, we are able to draw visitors in with content we've already entered. When updates are made to the reviews, they'll automatically be reflected in the module. We've implemented a helper class to centralize some of our data access and display functions. Several different layouts have been added so that we have multiple choices for display. This module can be used anywhere on the site and will show our visitors the variety of restaurants we've reviewed.


Learning Joomla! 1.5 Extension Development: Creating Modules, Components, and Plugins with PHP A practical tutorial for creating your first Joomla! 1.5 extensions with PHP
Published: June 2007
eBook Price: $23.99
Book Price: $34.99
See more
Select your format and quantity:

About the Author :


Books From Packt

Learning Joomla! 1.5 Extension Development: Creating Modules, Components, and Plugins with PHP
Learning Joomla! 1.5 Extension Development: Creating Modules, Components, and Plugins with PHP

Building Websites with Joomla! v1.0
Building Websites with Joomla! v1.0

Joomla! Template Design: Create your own professional-quality templates with this fast, friendly guide
Joomla! Template Design: Create your own professional-quality templates with this fast, friendly guide

Mastering Joomla! 1.5 Extension and Framework Development
Mastering Joomla! 1.5 Extension and Framework Development

Joomla! Cash
Joomla! Cash

Joomla! Accessibility
Joomla! Accessibility

Building Websites with Joomla! 1.5
Building Websites with Joomla! 1.5

Joomla! Web Security
Joomla! Web Security


 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
K
W
f
H
8
Q
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software