Using the JTable Class

  • PDF

Here is a quick intro to how to use the JTable class, a class within the Joomla framework that greatly simplifies database access.  The first step is to extend the JTable class with your new table class:

class TableRestaurant extends JTable 
   { 
   var $id = null; 
   var $name = null; 
   var $address = null; 
   var $comments = null; 
   var $comment_date = null;
   var $published = null; 
   function __construct(&$db) 
      {
      parent::__construct( '#__restaurant', 'id', $db );
      } 
   }

A few important considerations is that the JTable will have all the column names as defined as properties of the new class.  The column names and class properties have to have the exact same name - so $id corresponds to an id field, $name to a name fields, etc.  Once the table class is in place, you can use it in any Joomla! extension. To include the file, place this line in your extension's source code (use com_nameofyourcomponent in place of com_restaurant):

JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_restaurant'.DS.'tables');
 

To get an instance of the object, use this code:

$row =& JTable::getInstance('restaurant', 'Table');
 

Notice that the lowercase version of the suffix of your class name is used as the first parameter, with the prefix 'Table' as the second. Also, the getInstance() member function of JTable returns the object by reference instead of value; use =& to enforce this.

In a model class (extends JModel) you can also use:

$row =& $this->getTable('restaurant');

Updating is as simple as setting the row values in this manner.

$row->name = 'Jane''s Grill';
$row->address = 'One South Main';
$row->comments = 'Great sandwiches, worth the sometimes slow service.';
// Save results
$row->store();
 

Notice that the $row object of type TableRestaurant has all the columns we defined above.  When we call the store() method these rows are automatically stored in the database.  Our code above assumes that the id field will be auto-incremented on store(), so we are not providing a value for this field (as well as comment_date and published).  So this code will store a new value for this restaurant (essentially running and 'INSERT' query for us).  If we had provided value for the id field, the store() method would have instead 'UPDATE' query.

This approach is obviously much simpler code than the standard query string and $db code required without the JTable class.