

From Joomla! Documentation

< J1.5:Developing a MVC Component

Revision as of 08:32, 9 May 2013

Replacement filing cabinet.png



In the first three Parts, we have developed a MVC component that retrieves its data from a table in the database. Currently, there is no way to add data to the database except to do it manually using another tool. In the next Parts of this tutorial, we will develop an administrator section for our component which will make it possible to manage the entries in the database.

This Part, Part 4 - Creating an Administrator Interface, will be an article with no new source code for our Hello component but will describe some basic details and in-depth explanation of the MVC pattern. This intermediate chapter is not required to complete the Hello model so if you think you understand the basics continue with Developing a Model-View-Controller Component - Part 5 - Basic Backend Framework.

In the frontend solution (site section, parts 1,2 and 3) we developed the first part of our component. The frontend solution is based upon default Controllers, Views and Templates and you were "taken by the hand" and "left to trust" the default handling of the code. This is going to change in the Backend or Administration section of our Hello component ( parts 5 and 6) - we will have to develop all of the code that manages the application flow.

Site / Admin

Joomla! is a content management system. The frontend is used for presenting the users with content and allows certain logged in users to manipulate the content. The backend is responsible for administering the website framework (structuring / managing / controlling / maintaining). This division between (frontend) site-content and (backend) administration is a fundamental aspect of the Joomla! architecture.

Entrance points

From the XML file of our frontend example it was already obvious that there would be an administration part:

    <!--  Administration Menu Section --> 
    <menu>Hello World!</menu> 
    <!--  Administration Main File Copy Section --> 
    <files folder="admin">

Only the .sql files were of use and only during installation for our frontend view, the other two files have no content besides generating a blank page. Access your websites' file system at your hosting provider (or on your own server) and browse through the directories after installing the frontend com_hello component. You may have noticed that our Hello component is to be found twice:


These two sub-directories link to the previously explained site-content and administration. Administrator interactions explicitly go via the administrator sub-directory, where guest or registered users will enter the default entrance on the root:


Administrative users will have to log in, and after logging in they will enter your site via:


With the different access points it is easy to grasp that with setting up the administrator section the naming conventions have no dependency with the site section. Whilst the MVC pattern is also applicable for the administrator section this implies that identical Controllers, Views and Models naming can (and sometimes must) be used as in the site section.

MVC pattern interaction

MVC joomla.png
In Developing a Model-View-Controller Component - Part 1 the figure on the right was used to explain the focus of the first three parts of this Developing a Model-View-Controller Component tutorial. Now we will use this figure to explain how decisions are made on what is going to be displayed and how to manipulate this.

Example roll-out

For explanation purposes an easy to grasp example will be used. A library has the main function of lending books to registered users. Simply laid out there are three tables:

  • users
  • books
  • relation

Lets keep it all very simple. The users are addressed by Id and Name. The books are identified by Id and Title and the relation contains both Ids and the date of lending.

Library Example.png

The example is carefully chosen and will help in explaining the Joomla! architecture in more detail. The administrative side of our Hello component is not even that complex with only one table to manage. After the explanation of this Part it should be easy to follow the tutorial in the succeeding Parts.

Mapping a Joomla! MVC component from the example

In this example we will assume that administrative actions (add, edit, delete) are tasks that are to be performed by the administrator. For the frontend user only the view of the Relation table is interesting ("when do I have to bring back the books?"). This example shows the entire list and ignores all privacy stuff that could be taken care of by letting registered users only see their own books. (See: JUser object for making user deviations in template module).

Just like our frontend Hello component, for this library component only the default view is being used in the frontend. It lists the relational table, left joining the other two tables to obtain a human readable list of books with their corresponding due date.

Alice | One flew over ... | 12-aug-2009
Alice | Celeb talk        | 12-aug-2009
Mark  | Joomla!           | 15-aug-2009

With respect to the administration part it is important to understand that we have one default and three dedicated views, each controlling three tasks:

  • <Component name default view>
  • User administration
    • Add
    • Change
    • Delete
  • Book administration
    • Add
    • Change
    • Delete
  • Relation administration
    • Add
    • Change
    • Delete


The main controller of the admin section needs to differentiate between the different Adds, Changes or Deletes that are requested. This is taken care of by creating sub-controllers for each view for handling their specific tasks.


The controller is an important part of the MVC pattern. Not only does it take care of the requested tasks, it is also the initiator of instantiating the model with the same name and it is responsible for setting the view and the desired form for that view. The controller really justifies its name.

Within the controller it is good to make a difference between activating tasks (for example the edit selection from a menu) and resulting tasks (for example the result of an edit trigger is the posted data).

Typical controller functions look like:

function <activating task>()  // <-- edit, add, delete 
    JRequest::setVar( 'view', '[<componentname> | users | books | relation ]' );
    JRequest::setVar( 'layout', 'default'  );     // <-- The default form is named here, but in
                                                  // some complex views, multiple layouts might
                                                  // be needed.
function <resulting task>()  // <-- save, remove
        $model = $this->getModel('[<componentname> | users | books | relation ]');
        if(!$model->action() ) {    // <-- action could be delete() or store()
                $msg = JText::_( 'Error: Could not perform action' );
        } else {
                $msg = JText::_( 'Action executed' );
        $this->setRedirect( 'index.php?option=<componentname>', $msg );

A controller takes care of all tasks for that dedicated controller. After completing a resulting task the module will return to the main administration entrance point for that component, the main controller with the default view. Activating tasks enforce a new view with a form to display after first defining it.

The explicit definition of the form within a view might raise some eyebrows but our examples are too simple. For the general understanding and consistency this field should mostly be default. In complex views multiple forms could be defined within one view.


The Controllers interact with their equally named Model counter part. In the frontend view the Model was only used to retrieve data. The backend has more controllers and thus also more model files. The backend model files not only are responsible for delivering data to the viewer but also take care of tasks initiated from the controller. A good model contains all actions required to manage a single table in the database.



Separate views are of course also required. For views and subsequent forms no forced naming conventions are required (linking to views is taken care of in the controller). In the following listing the Administrative tasks are identified as a subset for the different views. This choice is totally random and maybe even non-logical but that doesn't matter for the explanation. Just for example purposes I added also a different view, a delete view, that could be used for all the deletes for all administrative tasks asking an "Are you sure" display.

<root>/administrator/views/<componentname>/view.html.php + .../tmpl/default.php
<root>/administrator/views/users/view.html.php           + .../tmpl/default.php
<root>/administrator/views/books/view.html.php           + .../tmpl/default.php
<root>/administrator/views/relation/view.html.php        + .../tmpl/default.php
<root>/administrator/views/delete/view.html.php          + .../tmpl/default.php

Note: In general it is good practice to maintain one form per view because the view.html.php still has to deliver the content. With some basic logic you can enable, disable certain content but if this logic is becoming too complex start considering splitting up the view.

Note: Sharing template parts amongst the different views (for uniform layouting of headers and titles of your component) can be done using the PHP include / require;. There is one slight problem ... how to make the logical reference? In my modules I have a collector bin for general to use sniplets. Because it involved the views and forms I put this general bin in the views directory. The variable $pathToGeneralView needs to be defined somewhere in the first lines of your file and you have to make sure that the logical reference path is correct (the '..'s). In the following example the files marked with a '*' use the following code:

./com_compname/views/general/navigate.header.php  <-- sniplet code for the header
./com_compname/views/general/navigate.footer.php  <-- sniplet code for the footer
./com_compname/views/mngtable1/tmpl/default.php *
./com_compname/views/mngtable2/tmpl/default.php *
$pathToGeneralView = strchr(dirname(__FILE__), dirname($_SERVER['SCRIPT_NAME']));
$pathToGeneralView = str_replace(dirname($_SERVER['SCRIPT_NAME']),'.',$pathToGeneralView );
$pathToGeneralView = $pathToGeneralView . "/../../general/";  <-- returning path from current position. 
<?php require_once $pathToGeneralView . 'navigate.header.php'; ?>
<P>Do something    
<?php require_once $pathToGeneralView . 'navigate.footer.php'; ?>

Another Way to do the same thing:

$pathToGeneralView = JPATH_COMPONENT_ADMINISTRATOR. "/views/general/";  <-- will return 'path/Joomla/administrator/components/com_example/views/general/'
<P>Do something    

Note: Giving the forms logical instead of the default naming is of course handy when having a lot of different views. Also, having that many default forms can make it difficult to determine the context. On the other hand, the view.html.php cannot be renamed, and one is always forced to look at the directory name for the view.

Essential Interaction Parameters

Everything is in place:

  • main and dedicated controllers;
  • main and dedicated models;
  • different views and their forms.

Just one big question remains: How to use them!

Three parameters are mandatory for letting Joomla! do its job:

  • option
  • controller
  • task

These three parameters are almost self explaining ;). The option part when developing a component is easy, always assign your component name to it. For component development consider this one as a constant, of course the Joomla! engine has more options than only components.

The controller and task parameters can be manipulated within your component anyway you want it to.

How it all works together

Looking at the simplified MVC picture Joomla! the logical flow of interaction goes the following way:

  1. What is my entrance point?
    • The Joomla! engine discovers a logged in administrator and sets the entrance point to <root>/administrator/index.php otherwise it will go to the <root>/index.php entrance.
  2. What option is requested?
    • The Joomla! engine reads the option variable and discovers that a component named <componentname> is requested. The entrance point becomes: <root>/administrator/components/com_<componentname>/<componentname>.php
  3. Is there need to access a dedicated controller?
    • The Joomla! engine reads the controller variable and discovers that a dedicated controller is required: <root>/administrator/components/com_<componentname>/controllers/<dedicatedcontroller>.php
  4. Is there a task that needs to be addressed?
    • The identified controller is handed the task value as parameter.
  5. The Model is derived from the controller and instantiated.
  6. The View and Form are set in the controller and initiated to become active.

How to add interaction

Within HTML there are two common ways to interact with Joomla!:

  1. reference to a link
  2. form submission post / get

Link reference for the Joomla! engine

Remember the activating tasks and resulting tasks mentioned earlier? Most activating tasks are initiated by a link. In case of the Library example the site section overview could be copied to the admin section. This default view will now be extended and every cell will become a link for editing the specific database element.

Using the Library example, the template PHP code without looping control will contain the following code:

$link = JRoute::_( 'index.php?option=com_library&controller=users&task=edit&cid='. $row->idu );
echo "<td><a href='$link'>{$row->name}</a></td>";
$link = JRoute::_( 'index.php?option=com_library&controller=books&task=edit&cid='. $row->idb );
echo "<td><a href='$link'>{$row->title}</a></td>";
$link = JRoute::_( 'index.php?option=com_library&controller=relation&task=edit&cid='. $row->idr );
echo "<td><a href='$link'>{$row->date}</a></td>";

Within each clickable field the three mandatory parameters to manipulate Joomla! can be identified. In addition there is one user parameter for handling the correct index in the controller task (cid). These parameter are separated by '&'. Do not use spaces in your variables, as this might screw-up parameter handling in certain browsers. After looping, all text entries will be clickable and trigger the corresponding controller with the correct row id in the associated table.

[Alice] | [One flew over ...] | [12-aug-2009]
[Alice] | [Celeb talk]        | [12-aug-2009]
[Mark]  | [Joomla!]           | [15-aug-2009]

Posting Form Data to the Joomla! Engine

After being initiated by an activating task, an input form view might be the result. The snippet of code below could be the result of clicking the first cell of the default component view that is clicked for editing ([Alice]:cid=3).

<form action="index.php" method="post">
  <input type="text" name="username" id="username" size="32" maxlength="250" value="<?php echo $this->user->name;?>" />
  <input type="submit" name="SubmitButton" value="Save" />
  <input type="hidden" name="option" value="com_library" />                  // <-- mandatory
  <input type="hidden" name="controller" value="hello" />                    // <-- mandatory
  <input type="hidden" name="task" value="save" />                           // <-- mandatory
  <input type="hidden" name="id" value="<?php echo $this->user->id; ?>" />   // <-- user parameter, index in database for [Alice]

The three Joomla! mandatory parameters are placed as hidden in the form. Hidden parameters are not shown in any way but will be added to the posting data.

Tip: when debugging this form, replace in the form tag method="post" temporarily with method="get". All posted parameters will be shown in the URL of your browser. If the module is working undo this change. For one reason it looks sharper without all the parameters being shown in the URL and you avoid motivating people to manipulate the browser URL themselves. Another reason is more technical and the simple explanation is that post methods (i.e. method="post") can contain more (complex) data. There is a third reason for using method="post" in form processing, and that is to increase security and prevent CSRF attacks on your site. method="post" should always be used when the resulting operation will modify the database.

Remark: In some developed modules you may notice that developers have also added the view parameter. This is bad programming whilst the controller(s) should take care of the view and the form.


The use of the three mandatory parameters and the different access points are clarified. Let's do something with this knowledge and extend the Hello component to the administrative section in the succeeding articles of this tutorial.


  • staalanden
  • jamesconroyuk