A tutorial explaining how simple component for Joomla! CMS 1.0 works, and how to create a component. One may wonder why to write about version 1.0 of Joomla!, when version 1.5 is almost ready (as of January 2007). I think version 1.0 is still a very good framework: one can get to know how Joomla! works, extend the PHP knowledge, and prepare for Joomla! 1.5, which is a lot different and more advanced. And since there rather will not be upgrade possible from 1.0 to 1.5, just migration (hopefully a fast and easy one, thanks to great developers), there may be still a lot of existing web sites working on Joomla! 1.0 for quite some time.
Official Joomla! web site contains a lot of useful information: help.joomla.org > Developer > Components Joomla! Development Wiki
There are of course tutorials of Joseph LeBlanc , and let's not forget about the most important part - security: Guide to more secure components
1. What is a component ? Component is mini-application working in Joomla! enviroment. There are a few component included with Joomla! installation: com_banners, com_contact, com_content, com_weblinks and others. These core components cannot be uninstalled, of course. Components show information in frontend and backend, as Joomla! does.
2. Simplest component The very simplest component has only two files: very_simple.php very_simple.xml Download zip file and install this sample component as usual in Joomla! Then create menu position pointing to the component. If there were no errors during installation the component should work now - it should display either "you are not logged in" or "welcome back" if you are logged in from frontend. Joomla! installer creates two folders for the component (com_simplest), and will put these files there: administrator/components/com_simplest/simplest.xml components/com_simplest/simplest.php The xml file is the "definition" file for the component - it contains details about it, list of files, SQL queries to perform during installation and after uninstalling it. The php file is the actual frontend of a component.
3. Typical component files The discussed component - JPortfSimple - has the following files: - admin.jportfsimple.php
- admin.jportfsimple.html.php
- toolbar.jportfsimple.php
- toolbar.jportfsimple.html.php
- install.jportfsimple.php
- uninstall.jportfsimple.php
- jportfsimple.xml
- jportfsimple.class.php
- jportfsimple.php
- jportfsimple.html.php
- CSS / jp.css
- HELP / english.html
- IMAGES
- LANG / english.php
During component installation there are two folders created within Joomla!: in administrator/components/com_jportfsimple - files 1 to 7 are copied here, this is so called backend and in components/com_jportfsimple - files 8, 9, 10 are copied here, this is frontend.
Location of remaining folders with files (11 to 14) depends on a developer. Location of all the above files and folders is defined in XML file, which is read during installation.
4. XML file jportfsimple.xml <?xml version="1.0" ?>
<mosinstall type="component">
<name>jportfsimple</name>
<creationDate>2007/01/01</creationDate>
<author>Konrad Gretkiewicz</author>
<copyright>This component in released under the GNU/GPL License</copyright>
<authorEmail>
This e-mail address is being protected from spam bots, you need JavaScript enabled to view it
</authorEmail>
<authorUrl>www.anetus.com</authorUrl>
<version>0.2</version>
<files>
<filename>index.html</filename>
<filename>jportfsimple.php</filename>
<filename>jportfsimple.html.php</filename>
<filename>jportfsimple.class.php</filename>
<filename>license.txt</filename>
<filename>_readme.txt</filename>
<filename>css/index.html</filename>
<filename>css/jp.css</filename>
<filename>images/index.html</filename>
<filename>images/no_image.jpg</filename>
<filename>lang/index.html</filename>
<filename>lang/english.php</filename>
</files>
<install>
<queries>
<query>
CREATE TABLE IF NOT EXISTS `#__jportfsimple_conf` (
`id` INT NOT NULL AUTO_INCREMENT,
`version` VARCHAR(20) NOT NULL,
`base_path` VARCHAR(50) NOT NULL,
`title` VARCHAR(100) NOT NULL,
`description` TEXT NOT NULL,
`css_file` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM
</query>
<query>
CREATE TABLE IF NOT EXISTS `#__jportfsimple_categories` (
`id` INT NOT NULL AUTO_INCREMENT,
`cat_name` TEXT NOT NULL,
`cat_info` TEXT NOT NULL,
`cat_path` TEXT NOT NULL,
`meta_desc` TEXT NOT NULL,
`meta_keywords` TEXT NOT NULL,
`cat_image` TEXT NOT NULL,
`cat_grp` int(11) NOT NULL default '0',
`ordering` int(11) NOT NULL default '0',
`access` TINYINT(1) NOT NULL default '0',
`published` TINYINT(1) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM
</query>
<query>
CREATE TABLE IF NOT EXISTS `#__jportfsimple_projects` (
`id` INT NOT NULL AUTO_INCREMENT,
`catid` TEXT NOT NULL,
`name` TEXT NOT NULL,
`description` TEXT NOT NULL,
`meta_desc` TEXT NOT NULL,
`meta_keywords` TEXT NOT NULL,
`proj_image` TEXT NOT NULL,
`proj_images_path` TEXT NOT NULL,
`userid` int(11) NOT NULL default '0',
`date` datetime NOT NULL,
`ordering` int(11) NOT NULL default '0',
`access` TINYINT(1) NOT NULL default '0',
`published` TINYINT(1) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM
</query>
<query>
INSERT INTO `#__jportfsimple_conf` VALUES (1,'0.2','images/stories/','JPortSimple','Sample description.','jp.css');
</query>
</queries>
</install>
<uninstall>
<queries>
<query>
DROP TABLE IF EXISTS `#__jportfsimple_conf`;
</query>
<query>
DROP TABLE IF EXISTS `#__jportfsimple_categories`;
</query>
<query>
DROP TABLE IF EXISTS `#__jportfsimple_projects`;
</query>
</queries>
</uninstall>
<installfile>
<filename>install.jportfsimple.php</filename>
</installfile>
<uninstallfile>
<filename>uninstall.jportfsimple.php</filename>
</uninstallfile>
<administration>
<menu>jportfsimple</menu>
<submenu>
<menu act="categories">Categories</menu>
<menu act="projects">Projects</menu>
<menu act="configure">Configuration</menu>
<menu act="info">About</menu>
</submenu>
<files>
<filename>index.html</filename>
<filename>admin.jportfsimple.php</filename>
<filename>admin.jportfsimple.html.php</filename>
<filename>toolbar.jportfsimple.php</filename>
<filename>toolbar.jportfsimple.html.php</filename>
<filename>logo.gif</filename>
<filename>help/index.html</filename>
<filename>help/english.html</filename>
</files>
</administration>
<params>
<param name="back_button" type="list" default="" label="Back Button" description="Show/Hide a Back Button, that returns you to the previous page">
<option value="">Use Global</option>
<option value="0">Hide</option>
<option value="1">Show</option>
</param>
<param name="item_navigation" type="list" default="" label="Navigation Bar" description="Show/Hide the Navigation bar">
<option value="">Use Global</option>
<option value="0">Hide</option>
<option value="1">Show</option>
</param>
<param name="display_num" type="list" default="50" label="Display Number" description="Number of items to be displayed by default">
<option value="6">6</option>
<option value="10">10</option>
<option value="16">16</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="50">50</option>
</param>
</params>
</mosinstall>
lines 1 to 9 - basic component's information: name, author, version 10 to 23 - frontend files 24 to 75 - SQL queries creating new tables (CREATE) with necessary structure in database. Here 3 tables are created: jos_jportfsimple_conf (few configuration values), jos_jportfsimple_categories (for categories) and jos_jportfsimple_projects (for projects). #_ is replaced during installation with table prefix defined for your site (usually jos_). Last query (line 81) loads sample configuration values.
76 to 88 - SQL queries run during uninstalling the component, removing old tables (DROP)
89 to 94 - defines files to run after installing and uninstalling component
96 to 102 - created backend menu, in Components
103 to 112 - backend files
114 to 134 - defines parameter which can be modified in menu position for given component
5. Frontend
Class file defines classes used in the component.
jportfsimple.class.php // no direct access
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
class jportfsimpleConf extends mosDBTable {
var $id = null;
var $version = null;
var $base_path = null;
var $title = null;
var $description = null;
var $css_file = null;
function jportfsimpleConf(&$db){
$this->mosDBTable('#__jportfsimple_conf', 'id', $db);
}
}
class jportfsimpleCategories extends mosDBTable {
var $id = null;
var $cat_name = null;
var $cat_info = null;
var $cat_path = null;
var $meta_desc = null;
var $meta_keywords = null;
var $cat_image = null;
var $cat_grp = null;
var $ordering = null;
var $access = null;
var $published = null;
function jportfsimpleCategories(&$db){
$this->mosDBTable('#__jportfsimple_categories', 'id', $db);
}
}
class jportfsimpleProjects extends mosDBTable {
var $id = null;
var $catid = null;
var $name = null;
var $description = null;
var $meta_desc = null;
var $meta_keywords = null;
var $proj_image = null;
var $proj_images_path = null;
var $userid = null;
var $date = null;
var $ordering = null;
var $access = null;
var $published = null;
function jportfsimpleProjects(&$db){
$this->mosDBTable('#__jportfsimple_projects', 'id', $db);
}
}
There are 3 classess defined, extending Joomla's class mosDBTable, each pointing to it's database table. Of course names of all fields here and in xml file (and database) must be the same. Main frontend file - jportfsimple.php - contains all logic for the component. It should not contain any output instructions, output should be done via .html.php file. jportfsimple.php // no direct access defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); global $mosConfig_live_site, $mosConfig_absolute_path, $mosConfig_lang, $database; // load .class.php and .html.php files for the component require_once( $mainframe->getPath( 'class' ) ); require_once( $mainframe->getPath( 'front_html' ) ); // load language file if (file_exists( $mosConfig_absolute_path. '/components/com_jportfsimple/lang/'. $mosConfig_lang. '.php')) include_once( $mosConfig_absolute_path.'/components/com_jportfsimple/lang/'.$mosConfig_lang.'.php'); else if (file_exists( $mosConfig_absolute_path. '/components/com_jportfsimple/lang/english.php')) include_once( $mosConfig_absolute_path.'/components/com_jportfsimple/lang/english.php'); // load configuration from database $database->setQuery('SELECT * FROM #__jportfsimple_conf' ); $conf_rows = $database -> loadObjectList(); if ($database -> getErrorNum()) { echo $database -> stderr(); return false; } $jpConf=$conf_rows[0]; // add CSS file for the component $mainframe->addCustomHeadTag( '<link href="'.$mosConfig_live_site.'/components/com_jportfsimple/css/'.$jpConf->css_file.'" rel="stylesheet" type="text/css" />' ); // get option and category $option = trim( mosGetParam ( $_REQUEST, 'option' )); $cat = (int) ( mosGetParam( $_REQUEST, 'cat' )); if (!$cat) { // if category not defined display all JP_categories(); } else { //display one category or one project $project = (int) ( mosGetParam( $_REQUEST, 'project' )); if ($project) { // display one project JP_project( $cat, $project); } else { // no project so display all in category JP_one_cat( $cat ); } }
First part of frontend file does the following: line 15, 16 - loads the required class and frontend html (jportfsimple.html.php) files 19 to 23 - loads language file, default is english.php in com_jportfsimple/lang folder. The name of the file must be the same as the language file name for your Joomla! site 26 to 32 - reads data from database table containing configuration parameters. They are stored in $jpConf object. line 35 - using Joomla function addCustomHeadTag the component loads the CSS file, what allows to style component display without changing whole site's CSS. 38 to 39 - function mosGetParam should be always used to get any input from user, with trim or (int) as additional security
41 to 62 - main frontend "logic": if category ($cat) is not defined, then display all categories, else try to read project number, and if it is defined, display one project, else display all projects in given category. That's it! Of course in case of more complicated component, here you would have case statement, with more variables.
Next, let's look at each function.
jportfsimple.php /** * Function displaying all categories */ function JP_categories() { global $database, $option, $mainframe, $jpConf; // get categories $database->setQuery('SELECT * FROM #__jportfsimple_categories ORDER BY ordering' ); $rows = $database -> loadObjectList(); if ($database -> getErrorNum()) { echo $database -> stderr(); return false; } // set page title $mainframe->setPageTitle( $jpConf->title ); display_categories( $option, $rows ); }
First function loads all categories from database table (lines 71 to 77), then sets component title as web page title, and calls display function.
jportfsimple.php /** * Function displaying one category */ function JP_one_cat( $cat ) { global $database, $mainframe, $option, $Itemid, $mosConfig_absolute_path, $jpConf; // get parameters associated with menu $params = new stdClass(); if ( $Itemid ) { $menu = new mosMenu( $database ); $menu->load( $Itemid ); $params = new mosParameters( $menu->params ); } else { $menu = ''; $params = new mosParameters( '' ); } // define parameters, if not set already $params->def('back_button', $mainframe->getCfg( 'back_button' ) ); $params->def('item_navigation', $mainframe->getCfg( 'item_navigation' )); $params->def('display_num', 50); // get category $database->setQuery('SELECT * FROM #__jportfsimple_categories WHERE id = '.$cat ); $categ = $database -> loadObjectList(); if ($database -> getErrorNum()) { echo $database -> stderr(); return false; } if ($categ) { if ($categ[0]->published) { // get projects in the category $database->setQuery('SELECT * FROM #__jportfsimple_projects WHERE catid='.$cat.' AND published=1 ORDER BY ordering ' ); $rows = $database -> loadObjectList(); if ($database -> getErrorNum()) { echo $database -> stderr(); return false; } // get limit values (needed for pagination) $limit = intval( mosGetParam ( $_REQUEST, 'limit', '' ) ); $limitstart = intval( mosGetParam ( $_REQUEST, 'limitstart', 0 ) ); $limit = $limit ? $limit : $params->get( 'display_num' ) ; if ( $total <= $limit ) { $limitstart = 0; $limit = $total; } //load pagination class require_once( $mosConfig_absolute_path . '/includes/pageNavigation.php' ); $pageNav = new mosPageNav( $total, $limitstart, $limit ); $pp=$categ[0]->cat_name; // add category name to pathway $mainframe->appendPathWay($pp); // set page title $mainframe->setPageTitle( $jpConf->title.' - '.$categ[0]->cat_name ); // set meta tags $mainframe->appendMetaTag( 'description', $categ[0]->meta_desc ); $mainframe->appendMetaTag( 'keywords', $categ[0]->meta_keywords ); display_one_cat($categ[0]->id, $categ[0]->cat_name, $categ[0]->cat_info, $categ[0]->cat_path, $rows, $params, $pageNav ); } else echo _COM_JP_ALB_NOT_PUBLISHED; } else echo _COM_JP_ALB_NOT_PUBLISHED; }
Lines 91 to 104 - reads parameters associated with component's menu position. These are the parameters defined at the end of xml file. 106 to 112 - reads category data from db.
114 to 117 - checks if there is a category with given id, and if it's published 118 to 124 - reads projects in given category 126 to 138 - gets pagination parameters (limit, limitstart), loads required class and created $pageNav object needed later 140 to 142 - adds category name to pathway line 144 - adds component title and category name to web site title bar 146 to 147 - adds meta tags (keywords and description) line 149 - all logic done, call display function
jportfsimple.php /** * Function displaying one project */ function JP_project( $cat, $project ) { global $database, $mainframe, $option, $Itemid, $jpConf; // get parameters associated with menu $params = new stdClass(); if ( $Itemid ) { $menu = new mosMenu( $database ); $menu->load( $Itemid ); $params = new mosParameters( $menu->params ); } else { $menu = ''; $params = new mosParameters( '' ); } // define parameters, if not set already $params->def('back_button', $mainframe->getCfg( 'back_button' ) ); $params->def('item_navigation', $mainframe->getCfg( 'item_navigation' )); // get category $database->setQuery('SELECT * FROM #__jportfsimple_categories WHERE id = '.$cat ); $categ = $database -> loadObjectList(); if ($database -> getErrorNum()) { echo $database -> stderr(); return false; } // get project $database->setQuery('SELECT * FROM #__jportfsimple_projects WHERE catid='.$cat.' AND id = '.$project.' AND published=1'); $proj = $database -> loadObjectList(); if ($database -> getErrorNum()) { echo $database -> stderr(); return false; } if ($proj) if ($proj[0]->published) { // add category name to pathway $pp="<a href=\"?option=com_jportfsimple&cat=".$categ[0]->id."&Itemid=".$Itemid."\">" .$categ[0]->cat_name."</a>"; $mainframe->appendPathWay($pp); // add project name to pathway $pp=$proj[0]->name; $mainframe->appendPathWay($pp); // set page title $mainframe->setPageTitle( $jpConf->title.' - '.$categ[0]->cat_name.' - '.$proj[0]->name ); // set meta tags $mainframe->appendMetaTag( 'description', $categ[0]->meta_desc ); $mainframe->appendMetaTag( 'keywords', $categ[0]->meta_keywords ); display_project( $categ[0]->id, $categ[0]->cat_name, $categ[0]->cat_path, $proj, $params); } else echo _COM_JP_ITEM_NOT_PUBLISHED; else echo _COM_JP_ITEM_NOT_PUBLISHED; }
Frontend view - jportfsimple.html.php - contains all output functions.
jportfsimple.html.php // no direct access defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); /** * Displaying all categories */ function display_categories( $option, &$rows ) { global $jpConf, $Itemid, $mosConfig_live_site; ?> <div id="jp_front"> <div id="jp_fronttitle"> <?php echo $jpConf-> title; ?> </div> <?php if ($jpConf->description) { ?> <div id="jp_frontdesc"> <?php echo $jpConf-> description; ?> </div> <?php } ?> <div id="jp_frontcategories"> <?php // if no rows then display: No categories defined ! if (! $rows) echo _COM_JP_NO_CAT; else foreach($rows as $row) { if ($row->published) { $link='<a href="'.sefRelToAbs( 'index.php?option='.$option.'&cat='.$row->id.'&Itemid='.$Itemid).'">'; echo '<div class="jp_frontcategory">'; echo '<div class="jp_frontcatname">'; echo $link. $row-> cat_name. '</a><br />'; echo '<div class="jp_frontcatimage">'; if ($row->cat_image) echo $link. '<img src="'. $mosConfig_live_site. '/'. $jpConf-> base_path. $row-> cat_image. '" border="0" alt="" /></a>'; echo '<div class="jp_frontcatinfo">'; } } bottom(); }
Lines 20 to 28 - shows component title and description line 33 - shows warning if there are no categories 35 to 54 - loop through categories and shows their name, description and image, if exists in line 38 function sefRelToAbs is used so links work when SEF is enabled As you can see, almost each displayed element is surrounded with <div> element, each with specific id or class. This way component display is not based on tables, but uses CSS.
jportfsimple.html.php /** * Displaying all projects in one category */ function display_one_cat( $catid, $catname, $catinfo, $catpath, &$rows, &$params, &$pageNav ) { global $jpConf, $option, $Itemid, $mosConfig_absolute_path, $mosConfig_live_site; echo '<div id="jp_front">'; echo '<div id="jp_cattitle">'._COM_JP_CAT_NAME. $catname. '</div>'; if ($catinfo) echo '<div id="jp_catinfo">'. $catinfo. '</div>'; echo '<div id="jp_onecat">'; // if no rows then display: No projects defined ! if (! $rows) echo _COM_JP_NO_PROJ; // go through all projects on given page for($i=$pageNav->limitstart; $i < ($pageNav->limitstart+$pageNav->limit) && $i < $pageNav->total; $i++) if ($rows[$i]) { $src=$jpConf->base_path.$catpath.'/'.$rows[$i]->proj_image; // if image defined exist, then show it, or show no_image.jpg if (! file_exists($mosConfig_absolute_path. '/'. $src) | is_dir($mosConfig_absolute_path. '/'. $src)) { $src=$mosConfig_live_site.'/components/com_jportfsimple/images/no_image.jpg'; } $link2=sefRelToAbs( 'index.php?option='.$option.'&cat='.$catid.'&project='.$rows[$i]->id.'&Itemid='.$Itemid); $prname=$rows[$i]->name; echo '<div class="jp_onecat_proj">'; echo '<div class="jp_onecat_img"><div class="jp_onecat_img2"><a href="'. $link2. '"><img src="'. $src. '" border="0" alt="" /></a></div></div>'; echo '<div class="jp_onecat_name"><a href="'. $link2. '">'. $prname. '</a></div>'; } // if item navigation enabled, then show page number if ( $params->get( 'item_navigation' ) && !($pageNav->limit == $pageNav->total) ) { echo '<div class="jp_pagination">'; $link='index.php?option='.$option.'&cat='.$catid.'&Itemid='.$Itemid; echo $pageNav-> writePagesLinks( $link ); } // if back button enabled, show it if ( $params->get( 'back_button' )) { echo '<div class="jp_back">'; mosHTML::BackButton ( $params ); } bottom(); }
line 76 - uses limit and limitstart (from $pageNav) to loop through all projects on given page 95 to 102 - shows page numbers, if it should
104 to 110 - shows back button, if enabled
jportfsimple.html.php /** * Displaying one project */ function display_project( $catid, $catname, $catpath, &$proj, &$params ) { global $database, $option, $Itemid, $jpConf, $mosConfig_absolute_path, $mosConfig_live_site; echo '<div id="jp_front">'; echo '<div id="jp_cattitle">'._COM_JP_CAT_NAME. $catname. '</div>'; echo '<div id="jp_projtop" >'._COM_JP_PROJ_NAME. $proj[0]-> name. '</div>'; echo '<div id="jp_projcont" >'; echo '<div id="jp_projimage" >'; $src=$jpConf->base_path.$catpath.'/'.$proj[0]->proj_image; // if image defined exist, then show it, or show no_image.jpg if (! file_exists($mosConfig_absolute_path. '/'. $src) | is_dir($mosConfig_absolute_path. '/'. $src)) { $src=$mosConfig_live_site.'/components/com_jportfsimple/images/no_image.jpg'; } echo '<img src="'. $src. '" border="0" alt="" />'; echo '<div id="jp_projdesc" >'; echo $proj[0]-> description. '<br />'; // if back button enabled, show it if ( $params->get( 'back_button' )) { echo '<div class="jp_back">'; mosHTML::BackButton ( $params ); } bottom(); } /** * Displaying component footer */ function bottom() { ?> <div align="right" style="float:right; width:60%; line-height:6px; padding:3px;"> <span class="small"> <br /><br /><br /> <a href="http://www.anetus.com/_r/jportfolio-component-for-joomla-cms" target="_blank" title="JPortfolio - component for Joomla! CMS">jp</a> </span> </div> <?php } ?>
Function display_project does exactly what the name suggests - it displays one project. Last one: bottom() - this is the function showing component footer, something like link to component web page and/or copyright information. It is not necessary to have, of course ;)
6. Remaining frontend files
There are few more files in frontend folder: language file, CSS file, and images. Language file - lang/english.php:
lang/english.php // no direct access defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); // main info DEFINE('_COM_JP_VERSION', '0.2'); DEFINE('_COM_JP_DESC', ' JPortfSimple - example of Joomla! component');
It's always good to provide language file, instead of using strings inside component, so the component can be translated easier. CSS file - css/jp.css: jp.css /* CSS for JPortSimple * * jp.css */ /*********************/ /* frontpage */ #jp_front { position:relative; float:left; width:99.5%!important; width:99.7%; margin:0px; } #jp_fronttitle, #jp_cattitle { position:relative; font-weight:bold; font-size: 16px; border-bottom: 2px solid #ccc; float:left; width:94%!important; width:97%; padding:10px; margin:1%; } and so on ......
CSS file contains all classes used in divs in the component. So far I haven't found a tool which would make checking language or css files easier. Now whatever change in the code is done - a text constant added or changed, or CSS class name changed - one has to remember to add/remove/change the respective one in the language or CSS file. |