From Joomla! Documentation

This page is a translated version of the page Model-View-Controller and the translation is 19% complete.
Outdated translations are marked like this.
Other languages:
Bahasa Indonesia • ‎English • ‎Kiswahili • ‎Nederlands • ‎català • ‎español • ‎français • ‎italiano • ‎日本語

Cette page décrit le modèle de conception Modèle-vue-Controleur tel qu'il est mis en œuvre dans Joomla.

Lorsque Joomla! traite la requête d'un utilisateur, comme un "GET" pour une page en particulier, ou un "POST" contenant des données de formulaire, une des premières actions de Joomla! est d'analyser l'URL pour déterminer quel composant devra traiter la demande et prendre le contrôle de ce composant.

Il le fera en exécutant le fichier PHP du composant du point d'entrée pour ce composant. Ainsi, si le composant s'appelle com_exemple, alors Joomla exécutera :

  • sur le site frontal : components/com_exemple/exemple.php
  • sur le back-end admin : administrator/components/com_exemple/exemple.php

Si vous développez un composant, vous pourriez en fait placer tout le code de votre composant dans ces deux fichiers exemple.php. Cependant, l'avantage de suivre le modèle MVC de Joomla est que vous pouvez utiliser pleinement les classes MVC de la bibliothèque de Joomla, ce qui réduit considérablement la quantité de code que vous devez écrire.

Aperçu de Joomla MVC

Joomla MVC

Code du point d'entrée

Le rôle principal du fichier PHP du point d'entrée (example.php pour com_example) est de déterminer le contrôleur à exécuter. Il le fait en se basant sur le paramètre de task (décrit plus en détail plus loin) et implique :

  • déterminer quelle classe de contrôleur doit être chargée
  • déterminer où trouver le code de cette classe
  • obtenir une instance de cette classe
  • appeler la méthode appropriée de cette classe.


Le contrôleur est chargé d'analyser la demande de l'utilisateur, de vérifier que l'utilisateur est autorisé à effectuer cette action et de déterminer comment satisfaire la demande. Ce dernier point implique :

  • déterminer quel(s) modèle(s) sera(seront) nécessaire(s) pour satisfaire la demande, et créer une instance de ce modèle
  • faire des appels aux méthodes du modèle pour effectuer les mises à jour nécessaires de la base de données
  • déterminer quelle vue doit être utilisée pour présenter la page Web à l'utilisateur, et créer une instance de cette vue, ou..,
  • si l'utilisateur doit être redirigé vers une autre URL, déterminer cette URL de redirection.


La vue spécifie ce qui doit apparaître sur la page Web et rassemble toutes les données nécessaires à la production de la réponse HTTP.

Après que le contrôleur ait créé l'instance de la vue, il appelle la méthode setModel() de la vue et passe l'instance du modèle. De cette façon, la vue sait quel modèle utiliser, et appelle les méthodes du modèle pour obtenir les données nécessaires au retour vers l'utilisateur.


The view doesn't output HTML but delegates this to the layout. The layout contains PHP code which runs within the context of the method (usually display()) of the view, which means that if the view holds the response data in, for example, $this->items then the layout can access that same $this->items when it is outputting the HTML.

Separating the view and layout like this enables another level of flexibility, as you can easily set up a layout override to output the view data using your own preferred HTML.


The model encapsulates the data used by the component. In most cases this data will come from a database, either the Joomla database, or some external database, but it is also possible for the model to obtain data from other sources, such as via a web services API running on another server. The model is also responsible for updating the database where appropriate. The purpose of the model is to isolate the controller and view from the details of how data is obtained or amended.

If the component is displaying a form which is defined in XML using the Joomla Form approach, the model handles the setting-up and configuration of the Form instance, ready for the layout to output fields using $form->renderField() etc.

Subsequent Processing

The output from the component (specifically the HTML output from the layout) is not directly output as the HTTP response, but rather is captured and buffered by Joomla. Once the layout has generated the output, the component hands control back to the Joomla framework which then loads and executes the template. The template combines the output from the component, and any modules that are active on the current page, so that it can be delivered to the browser as a single page.

Le paramètre task de la requête HTTP

Joomla uses the HTTP Request task parameter to determine which controller should be used. The task parameter can be sent in an HTTP GET or an HTTP POST – in fact, Joomla doesn't really make a distinction between GET and POST parameters – but the task parameter is just an ordinary HTTP parameter, nothing special.

In the core Joomla entry point PHP files you'll almost always see something like:

$controller = JControllerLegacy::getInstance('example');

with example replaced by Contact, Content, Modules etc.

The getInstance() method of JControllerLegacy (or BaseController, (as it is now known after Joomla 3.8) is where all the magic happens. It

  • examines the task parameter
  • based on this parameter it decides which controller class to load, and in which file it expects to find that class
  • creates an instance of this controller class (which gets returned from this function)
  • resets the task parameter to be the method which should be called.

The next line of code ($controller->execute(JFactory::getApplication()->input->get('task'));) then calls the execute() method of the controller instance with the parameter which is now the method to run, and the execute method basically runs the passed-in method.

The task parameter is of the form x.y, where x represents the controller type and y the method to call. The controller type may be absent in which case the method in controller.php is run. If the controller type is present then one of the controllers in the controllers folder is used. If the task parameter is not set at all then the display() method in controller.php is run. The table below lists the possibilities for a component called com_example.

Form of task Controller file Controller class Controller method
controllerType.method controllers/controllerType.php ExampleControllerControllerType method
eg items.process controllers/items.php ExampleControllerItems process
method(no controllerType set) controller.php ExampleController method
(task not set) controller.php ExampleController display

The above is true both for the Frontend site and the Backend Administrator, except that for the Administrator it all happens under the administrator folder.

Modèle Post/Request/Get


Joomla follows the Post/Redirect/Get pattern, which means that when a user submits a form in an HTTP POST, then rather than Joomla responding to the POST with an HTML page, redirects to another page which the browser will access with an HTTP GET.

This is typified when the Administrator displays the Content/Articles page, as shown in the first diagram. The action to be performed is indicated by the task parameter, and both it and related data are sent in the POST request. Once the action is performed the next web page to be displayed is defined in the HTTP Redirect.


The second diagram depicts the pattern when an administrator edits an article. In this case there is the additional step of displaying the edit form, which again Joomla handles by sending an HTTP Redirect in response to the original request to edit an article. (At point 3 Joomla (in the BaseDatabaseModel) stores an edit id in the session and component controllers check this id at point 4 to ensure that users can't just specify the URL of the form directly without going through point 3).

The red numbers in green circles in the diagram refer to the different types of HTTP requests which Joomla is handling. We'll see in the next section that different Joomla MVC classes have been defined to cater to these five cases.

Joomla MVC Classes

There are several Joomla library MVC classes under libraries/src/MVC and this section aims to give an overview of these classes and explain when your own component should use each class. It doesn't attempt to provide a full description of each class's functionality.

MVC Base Classes

The 3 MVC base classes are BaseController (previously called JControllerLegacy), HtmlView (previously called JViewLegacy) and BaseDatabaseModel (previously called JModelLegacy). The functionality within BaseController includes:

  • the getInstance() and execute() methods described above, which together find the component controller and run the appropriate method, all based on the value of the task parameter.
  • functions for finding the appropriate view class to use (based on the setting of the view parameter within the HTTP request), and where to look for the PHP file which should contain this class.
  • running the class PHP file, and creating an instance of the view
  • using the BaseDatabaseModel::getInstance() method to obtain an instance of the model which is associated with the view being used
  • the default display() method, which gets instances of the view and model classes (including providing the view instance with a link to the model instance), and then calls the display() method of the view class.

The HtmlView class includes:

  • the display() method, which runs the layout file
  • code for finding the layout file, taking into account a layout override which may have been put into the template folder structure
  • code for setting the model instance, and subsequently retrieving it
  • a general purpose get() method which when called like get("something") converts it into a call on the model $model->getSomething().

The BaseDatabaseModel contains:

  • the static getInstance() method which finds the PHP file containing the code for the model, runs it, and returns an instance of the model class.
  • code for getting an instance of the Table class which will handle the interface to the underlying database table for this component.
  • base code for creating a model "state". This feature is useful if the component and/or several modules shown on the web page all use the same base data. In this case they may share the same model instance and the model "state" acts like a container for sharing the values of items across the component and modules.

In general, using base classes is a good option if your component is displaying a single item on a site page.

Higher-level View Classes

There are 3 higher-level view classes, all of which inherit directly from the HtmlView base class. The name of the class (and so the name of the PHP file) gives a good indication of its use:

  • CategoryView – for displaying a category and its children
  • CategoriesView – for displaying all the categories at a certain level in the category hierarchy, and the number of items associated with each category
  • CategoryFeedView – for generating a feed.

Using the CategoryView or CategoriesView classes could be useful if you're following the paradigm of how com_content outputs this information on the site, but otherwise probably not so useful.

The CategoryFeedView class will help if you're providing a feed, as described in Adding a Feed.

Higher-level Controller Classes

There are 2 higher-level controller classes, each of which inherit from BaseController.

AdminController contains methods which handle the types of operations that can be performed on multiple items, for example:

  • delete
  • checking-in
  • changing the publishing state
  • changing the relative ordering of records

However, note that it doesn't support the operations enabled by the Batch button on e.g. the Content/Articles page. The code generally calls the related model method to effect the operation, sets up the message based on the success of the model operation, and sets up the redirect back to the same page. For this reason it's very useful in case 2 shown in the diagrams above in Post/Request/Get pattern.

The name AdminController suggests that this controller is to be used only on the Backend Administrator functionality, however, this is not the case. It's appropriate to use it on the site Frontend as well.

FormController contains methods which are associated with editing an individual item

  • handling a request to edit an item – which involves checking that the user is allowed to edit the item and that it isn't already checked out, and if these checks pass then the item is checked out (if that component has enabled checkout) and a redirect is issued to display the edit form
  • handling a request to add a new item – which involves checking that the user is allowed to edit the item and results in a redirect to display a blank edit form
  • handling the Save of an item being edited or created from new – the code checks that the user is allowed to perform the operation and calls the appropriate model method to save the new/edited item.
  • handling the Cancel of an edit, redirecting the user back to the appropriate page (and checking-in the record if required).
  • handling the operations initiated through the Batch button

The FormController is thus well suited to cases 3 and 5 shown in the diagrams above in Post/Request/Get pattern.

Higher-level Model Classes

Model hierarchy.jpg

The diagram shows the inheritance tree of the Joomla library MVC models.

ItemModel is almost the same as BaseDatabaseModel. It just has an extra getStoreId() method which is relevant when you have a component and/or several modules sharing the same model and you want to distinguish between data sets relevant to each.

In addition to getStoreId(), ListModel has capability relating to obtaining a set of records for display on a web page, including support for pagination. Note that the pagination capability may still be slightly different between the Frontend and Backend – see this issue. The ListModel is useful for supporting case 1 in the above diagrams.

FormModel includes support for Joomla forms, both for setting up the form so that it can be displayed, and also so that the form data sent in the POST can be validated. In addition, it has methods for implementing checkin and checkout of database records. So it's suitable for handling cases 3 and 4 in the diagrams above.

AdminModel extends FormModel, so it has all the capability for handling forms, but in addition has methods for handling database updates – including capability for adding, updating and deleting records – as well as support for handling operations in batch. So it's suitable for handling cases 2 and 5 in the diagrams above. As with the AdminController, this model is not just appropriate for the administrator functionality, but can be used on the Frontend as well.

However, although the FormModel and AdminModel support different cases in the flow associated with editing a record, in practice it's common to use the same model for all the different steps of the flow. All the Joomla core components use the same model across these steps, and so they all extend AdminModel instead of FormModel.

Something to be aware of if you are using the same model across the "edit item" flow is that your model code is performing 2 purposes:

  1. preparing data to be shown on a web page
  2. preparing a form, either for display on a web page or for validating POST data

When you're using the model because you're handling a POST (i.e. cases 3 and 5 in the diagram) then any effort expended in preparing the data for a web page is going to be wasted. (In fact, in the FormController getModel() method call, the parameter $config is set to array('ignore_request' => true) by default, which results in the model's populateState method not being run, perhaps to save this wasted effort.)


The choice of which controller and model classes to extend is easier on the Backend, because you just follow the pattern of the Joomla core components.

Pour la partie avant, voici un guide approximatif :

Simply displaying a record or a set of records, without providing the ability to change anything:

  • controller extends BaseController
  • model extends BaseDatabaseModel or (particularly if you're sharing a model between a component and modules) ItemModel if it's a single record, ListModel if it's multiple records.

Displaying a form with multiple records (but the form isn't defined in an XML file), including the providing the ability to select several records and apply some sort of operation to them (eg delete, publish):

  • controller extends BaseController
  • model extends ListModel – except if you're using the same model for displaying the form and handling the updates, in which case use AdminModel

Handling the HTTP POSTs from that form in subcontrollers:

  • controller extends AdminController
  • model extends AdminModel

Afficher un formulaire avec un seul enregistrement, où le formulaire est défini dans un fichier XML, et permettre à l'utilisateur de le modifier, ou un enregistrement vierge et permettre à l'utilisateur de créer un enregistrement :.

  • contrôleur étend BaseController
  • modèle étend FormModel - sauf si vous utilisez le même modèle pour afficher le formulaire et gérer les mises à jour (comme c'est généralement le cas), auquel cas utilisez AdminModel

Handling the HTTP POSTs from that form in subcontrollers:

  • controller extends FormController
  • model extends AdminModel

Voir également

===Série développement de Composant===

Développer un composant MVC pou Joomla 4.x

Développer un composant MVC pou Joomla 3.x