J4.x

J4.x: Creazione di un semplice modulo

From Joomla! Documentation

Revision as of 06:14, 23 January 2022 by Sportegioco (talk | contribs) (Created page with "I files <tt>language/en-GB/mod_foo.ini</tt> e <tt>language/en-GB/mod_foo.sys.ini</tt> sono usati per tradurre il testo nel frontend e nel backend. Nota che la struttura del fi...")
Other languages:
Deutsch • ‎English • ‎Nederlands • ‎français • ‎italiano • ‎polski • ‎português • ‎Ελληνικά • ‎русский
Joomla! 
4.x
>Tutorial
Creazione di un modulo semplice per Joomla 4.x

Questo è un tutorial su come creare un modulo semplice per la versione di Joomla 4x.

Introduzione

Joomla! 4 offre cinque tipi di estensioniː

  • Componenti
    Un componente è la parte principale del sito. Un componente gestisce la manipolazione dei dati così come l'input e l'archiviazione nel database. Un componente nella maggior parte dei siti è l'obiettivo principale della pagina.
  • Moduli
    Un modulo è un componente aggiuntivo del sito che estende la funzionalità. Un modulo di solito occupa una porzione secondaria della pagina Web e non è considerato l'obiettivo principale di una pagina. Può essere visualizzato su diverse posizioni e puoi scegliere su quali voci di menu attive dovrebbe essere visualizzato. I moduli sono estensioni leggere e flessibili. Sono usati per piccoli bit della pagina che sono generalmente meno complessi e possono essere visti attraverso diversi componenti.
  • Plugins
    Un plugin manipola l'output che è già stato generato dal sistema. In genere non viene eseguito come parte separata del sito. Prende dati da altre fonti (ad esempio il contenuto) e manipola questi dati prima di visualizzarli. Un plugin in genere funziona dietro le quinte.
  • Le lingue
    Probabilmente le estensioni più basilari sono le lingue. In sostanza i file del pacchetto linguistico consistono in coppie chiave / valore, che forniscono la traduzione di stringhe di testo statiche, assegnate all'interno di Joomla! codice sorgente.
  • Templates
    Un template è fondamentalmente il design del tuo sito web Joomla!.

Joomla! 4 è costruito usando cinque diverse applicazioni:

  • Installazione (utilizzata per l'installazione di Joomla e deve essere cancellata dopo l'installazione)
  • Amministratore (back-end - utilizzato per la gestione del contenuto);
  • Pubblico o sito (frontend - utilizzato per la visualizzazione di contenuti);
  • CLI (utilizzato per accedere a Joomla sulla riga di comando e per i lavori cron);
  • API (servizi Web - utilizzati per creare API per contenuti accessibili dal computer):

L'applicazione di installazione viene utilizzata una volta. La parte di amministratore e la parte pubblica sono utilizzate attraverso il concetto di componenti con moduli . Ogni modulo ha un unico punto di ingresso situato nei moduli e di conseguenza nella directory administrator/modules . Questo punto di ingresso è chiamato mod_modulename/mod_modulename.php (il prefisso mod_ è una traccia storica). Il punto di ingresso per il modulo di accesso è ad esempio /mod_login/mod_login.php

Requisiti

Hai bisogno di Joomla! 4.x per questo tutorial (come di scrivere attualmente Joomla! 4.0.0.0-alpha6-dev)

Puoi scaricare Joomla! 4 su GitHub, sul Developer website oppure puoi creare un sito Web gratuito su https://launch.joomla.org.


Creazione di un modulo semplice/Sviluppo di un modulo base - Parte 1

Puoi vedere molti esempi di moduli nello standard Joomla! installare. Per esempio:

  • Menù
  • Ultime notizie
  • Modulo di accesso
  • e molti altri.

Questo tutorial spiegherà come creare un modulo semplice. Attraverso questo tutorial imparerai la struttura di base dei file di un modulo Joomlaǃ 4. Questa struttura di base può quindi essere ampliata per produrre moduli più elaborati

Struttura del file

Ci sono alcuni file di base che vengono utilizzati nel modello standard di sviluppo del modulo:

  • mod_foo.php - Questo file è il punto di ingresso principale per il modulo. Eseguirà tutte le routine di inizializzazione necessarie, chiamerà le routine di supporto per raccogliere tutti i dati necessari e includerà il modello che visualizzerà l'output del modulo.
  • mod_foo.xml - Questo file contiene informazioni sul modulo. Definisce i file che devono essere installati da Joomla! installatore e specifica i parametri di configurazione per il modulo.
  • tmpl/default.php - Questo è il modulo del template. Questo file prenderà i dati raccolti da mod_foo.php e genererà l'HTML da visualizzare nella pagina.
  • language/en-GB/mod_foo.ini e language/en-GB/mod_foo.sys.ini - Questi sono i file che forniscono il testo in inglese del Regno Unito.


Creazione di mod_foo.php

Il file mod_foo.php eseguirà le seguenti attività:

  • Importa la classe ModuleHelper nell'ambito corrente. Ne abbiamo bisogno in seguito per visualizzare l'output.
  • Includere il modello per visualizzare l'output

La classe helper viene importata nel nostro scope corrente all'inizio del file

use Joomla\CMS\Helper\ModuleHelper;

Infine includiamo il modello per visualizzare l'output tramite

require ModuleHelper::getLayoutPath('mod_foo', $params->get('layout', 'default'));

File mod_foo.php completato Il file mod_foo.php completo è il seguente:

<?php
/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */

// No direct access to this file
defined('_JEXEC') or die;

use Joomla\CMS\Helper\ModuleHelper;

require ModuleHelper::getLayoutPath('mod_foo', $params->get('layout', 'default'));

Nota a margineː In Joomla 3x di solito usavi una linea tipo questa $moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));. Non hai più bisogno di questo. Vedi questo PRː https://github.com/joomla/joomla-cms/pull/17447.

L'unica riga che non abbiamo spiegato finora è la prima riga defined('_JEXEC') or die;. Questa riga verifica che questo file sia incluso dall'applicazione Joomla. Ciò è necessario per prevenire l'iniezione di variabili e altri potenziali problemi di sicurezza

Creazione di tmpl/default.php

Il file default.php è il modello che mostra l'output del modulo.

File tmpl/default.php completo

Il codice per il file tmpl/default.php è il seguente:

<?php
/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */

// No direct access to this file
defined('_JEXEC') or die;

echo '[PROJECT_NAME]';

Un punto importante da notare è che il file modello ha lo stesso ambito del file mod_foo.php file.Significa che una variabile può essere definita nel file mod_foo.php e quindi utilizzata nel file modello senza dichiarazioni aggiuntive o chiamate di funzione.

Creazione di mod_foo.xml

Il file mod_foo.xml è il file di installazione. La maggior parte delle voci sono autoesplicative.

File mod_foo.xml completo

Il codice per il file mod_foo.xml è il seguente:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="4.0" client="site" method="upgrade">
    <name>MOD_FOO</name>
    <creationDate>[DATE]</creationDate>
    <author>[AUTHOR]</author>
    <authorEmail>[AUTHOR_EMAIL]</authorEmail>
    <authorUrl>[AUTHOR_URL]</authorUrl>
    <copyright>[COPYRIGHT]</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <version>1.0</version>
    <description>MOD_FOO_XML_DESCRIPTION</description>
    <files>
        <filename module="mod_foo">mod_foo.php</filename>
        <folder>tmpl</folder>
        <folder>language</folder>
        <filename>mod_foo.xml</filename>
    </files>
</extension>

Creating the language files

I files language/en-GB/mod_foo.ini e language/en-GB/mod_foo.sys.ini sono usati per tradurre il testo nel frontend e nel backend. Nota che la struttura del file della lingua è stata aggiornata in Joomla 4 e i prefissi della lingua sui singoli file in una cartella della lingua non sono più necessari

The code for language/en-GB/mod_foo.sys.ini is as follows:

MOD_FOO="[PROJECT_NAME]"
MOD_FOO_XML_DESCRIPTION="Foo Module"

The code for language/en-GB/mod_foo.ini is as follows:

MOD_FOO="[PROJECT_NAME]"
MOD_FOO_XML_DESCRIPTION="Foo Module"

The .sys.ini file is used to translate the description of the extension upon installation, where as the .ini file is used to translate the remaining strings and the description when viewing your extension.

More information about language files can be found here.


Test your module

Now you can zip all files and install them via the Joomla Extension Manager.
After that you can choose your module in the module manager, when you create a new site module.

In the frontend, you will see your module like displayed in the next image.

Conclusione

Module development for Joomla is a fairly simple, straightforward process. Using the techniques described in this tutorial, an endless variety of modules can be developed with little hassle.

You can find boilerplates hereː

The sample files for this Tutorial can be found hereː


Add a helper class using namespaces - Part 2

Requirements

You need Joomla! 4.x for this tutorial (as of writing currently Joomla! 4.0.0-alpha6-dev)

Namespaces

With PHP 5.3, the namespaces came into their own. In other programming languages for a long time in use, these small structures now also help us with the clarity of our code.

Namespaces are separate areas in which certain logical things (in our case, classes, interfaces, functions, and constants) can live. These areas provide encapsulation of the code and prevent name conflicts.

Let's take a look how to use them in Joomla 4. We use the helper file for this.

File Structure

We will create/change the following files:

  • Helper/FooHelper.php - This is the file we use here as an example. We have to create it.
  • mod_foo.php - In this file, we will mainly load the namespace.
  • tmpl/default.php - In this file, we will demonstrate how the data of a helper can be displayed.
  • mod_foo.xml - We create a new directory with a new file. This must be installed during the installation. For this we have to specify them in this file.

Creating Helper/FooHelper.php

Our new helper class should belong to a namespace. We achieve this with the following code. It is important, that this line is at the beginning of the file.

namespace Joomla\Module\Foo\Site\Helper;

Then we create a simple class with a simple method. Of course you can do a lot more here. Take a look at the Joomla core methods. Here are many examples. They show you first-hand what options you have.

Completed Helper/FooHelper.php

The complete FooHelper.php file is as follows:

<?php
/**
 * @package     Joomla.Site
 * @subpackage  mod_foo
 *
 * @copyright   Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

namespace Joomla\Module\Foo\Site\Helper;

// No direct access to this file
defined('_JEXEC') or die;

/**
 * Helper for mod_foo
 *
 * @since  4.0
 */
class FooHelper
{
	/**
	 * Retrieve foo test
	 *
	 * @param   Registry        $params  The module parameters
	 * @param   CMSApplication  $app     The application
	 *
	 * @return  array
	 */
	public static function getText()
	{
		return 'FooHelpertest';
	}
}


Editing mod_foo.php

Our new helper class is imported to our current scope at the beginning of the file.

use Joomla\Module\Foo\Site\Helper\FooHelper;

Last use the helper file for testing if it is loaded correctlyː

$test  = FooHelper::getText($params, $app);

Completed mod_foo.php file

The complete mod_foo.php file is as follows:

<?php
/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */

// No direct access to this file
defined('_JEXEC') or die;

use Joomla\CMS\Helper\ModuleHelper;
use Joomla\Module\Foo\Site\Helper\FooHelper;

$test  = FooHelper::getText();

require ModuleHelper::getLayoutPath('mod_foo', $params->get('layout', 'default'));

Editing tmpl/default.php

In this file you make only a small change to demonstrate in the frontend that your helper file is working properly. You only add the value of the variable at the end of the current output.

echo '[PROJECT_NAME]' . $test;

Completed tmpl/default.php

The complete tmpl/default.php file is as follows:

<?php
/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */

// No direct access to this file
defined('_JEXEC') or die;

echo '[PROJECT_NAME]' . $test;

Editing mod_foo.xml

First you have to add a line, so that the namespace is set automatically in Joomla. After this change, you have to re-install your module. A simple change in an already installed module is not enough. If you are doing local development you can also delete the files libraries/autoload_psr4.php and it will automatically be re-created. After inserting and installing, the namespace is known by the loader JPATH_LIBRARIES . '/autoload_psr4.php'.

<namespace>Joomla\Module\Foo</namespace>

Joomla! should copy your helper file when installing the module. So Joomla! needs to know your helper file. For this, you need to add the following line to your XML file.

<folder>Helper</folder>

Completed mod_foo.xml

The complete mod_foo.xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="4.0" client="site" method="upgrade">
    <name>MOD_FOO</name>
    <creationDate>[DATE]</creationDate>
    <author>[AUTHOR]</author>
    <authorEmail>[AUTHOR_EMAIL]</authorEmail>
    <authorUrl>[AUTHOR_URL]</authorUrl>
    <copyright>[COPYRIGHT]</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <version>1.0</version>
    <description>MOD_FOO_XML_DESCRIPTION</description>
    <namespace>Joomla\Module\Foo</namespace>
    <files>
        <filename module="mod_foo">mod_foo.php</filename>
        <folder>tmpl</folder>
        <folder>Helper</folder>
        <folder>language</folder>
        <filename>mod_foo.xml</filename>
    </files>
</extension>

Metti alla prova il tuo modulo

Ora puoi comprimere tutti i file e installarli tramite Joomla Extension Manager. After that you can choose your module in the module manager, when you create a new site module.

In the frontend you will see your module like displayed in the next image. The text from your helper file is displayed.

Conclusione

Come puoi vedere, una volta entrati nei namespace, non sono più così complicati. Nei grandi progetti possono portare molti benefici. Tuttavia, dovremmo pianificare gli spazi dei nomi, altrimenti sarà presto più dispendioso in termini di tempo.

Puoi trovare le piastre di riscaldamento quiː

The sample files for this Tutorial can be found hereː


Customizationː Add parameters via form fields - Part 3

Requirements

You need Joomla! 4.x for this tutorial (as of writing currently Joomla! 4.0.0-alpha6-dev)

Customization with form fields and parameters

Form fields give a great deal of customization in Joomla and for modules are the sole way of allowing the user to tweak the module to the needs of their site.

In this case we are going to extend our previous example using a url field for inserting a domain that we can use as link in the front end. To allow this to happen we will use the URL Form Field type.

After that, we insert parameters that allow to use standard functionality of Joomla.

Let's take a look on how to use them in Joomla 4.

File Structure

We will change the following files:

  • mod_foo.xml - This is the file where we add the fields.
  • tmpl/default.php - In this file demonstrate how the data of a field can be used.
  • language/en-GB/en-GB.mod_foo.ini - Here we use a language string so that the field can be labeled correctly in different languages.

Editing mod_foo.xml

First we set a custom parameter.

<field
    name="domain"
    type="url"
    label="MOD_FOO_FIELD_URL_LABEL"
    filter="url"
/>

Then we insert Joomla default fields, so that we can use cache, moduleclass-suffix and layouts.

<field
    name="layout"
    type="modulelayout"
    label="JFIELD_ALT_LAYOUT_LABEL"
    class="custom-select"
/>

<field
    name="moduleclass_sfx"
    type="textarea"
    label="COM_MODULES_FIELD_MODULECLASS_SFX_LABEL"
    rows="3"
/>

<field
    name="cache"
    type="list"
    label="COM_MODULES_FIELD_CACHING_LABEL"
    default="0"
>
    <option value="1">JGLOBAL_USE_GLOBAL</option>
    <option value="0">COM_MODULES_FIELD_VALUE_NOCACHING</option>
</field>

<field
    name="cache_time"
    type="number"
    label="COM_MODULES_FIELD_CACHE_TIME_LABEL"
    default="0"
/>

<field
    name="cachemode"
    type="hidden"
    default="itemid"
>
    <option value="itemid"></option>
</field>

Completed mod_foo.xml

The complete mod_foo.xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="4.0" client="site" method="upgrade">
    <name>MOD_FOO</name>
    <creationDate>[DATE]</creationDate>
    <author>[AUTHOR]</author>
    <authorEmail>[AUTHOR_EMAIL]</authorEmail>
    <authorUrl>[AUTHOR_URL]</authorUrl>
    <copyright>[COPYRIGHT]</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <version>1.0</version>
    <description>MOD_FOO_XML_DESCRIPTION</description>
    <namespace>Joomla\Module\Foo</namespace>
    <files>
        <filename module="mod_foo">mod_foo.php</filename>
        <folder>tmpl</folder>
        <folder>Helper</folder>
        <folder>language</folder>
        <filename>mod_foo.xml</filename>
    </files>
    <config>
        <fields name="params">
            <fieldset name="basic">
                <field
                    name="domain"
                    type="url"
                    label="MOD_FOO_FIELD_URL_LABEL"
                    filter="url"
                />
            </fieldset>
            <fieldset name="advanced">
                <field
                    name="layout"
                    type="modulelayout"
                    label="JFIELD_ALT_LAYOUT_LABEL"
                    class="custom-select"
                />
                <field
                    name="moduleclass_sfx"
                    type="textarea"
                    label="COM_MODULES_FIELD_MODULECLASS_SFX_LABEL"
                    rows="3"
                />
                <field
                    name="cache"
                    type="list"
                    label="COM_MODULES_FIELD_CACHING_LABEL"
                    default="0"
                >
                    <option value="1">JGLOBAL_USE_GLOBAL</option>
                    <option value="0">COM_MODULES_FIELD_VALUE_NOCACHING</option>
                </field>
                <field
                    name="cache_time"
                    type="number"
                    label="COM_MODULES_FIELD_CACHE_TIME_LABEL"
                    default="0"
                />
                <field
                    name="cachemode"
                    type="hidden"
                    default="itemid"
                >
                    <option value="itemid"></option>
                </field>
            </fieldset>
        </fields>
    </config>
</extension>

Editing tmpl/default.php

We can use the value of the parameter for creating a hyperlink in the frontend. We can access the value via the variable $params.

$domain = $params->get('domain', 'https://www.joomla.org');

Later we set use this value for creating the hyperlink.

<a href="<?php echo $domain; ?>">
	<?php echo '[PROJECT_NAME]' . $test; ?>
</a>

Completed tmpl/default.php file

The complete tmpl/default.php file is as follows:

<?php
/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */

// No direct access to this file
defined('_JEXEC') or die;

$domain = $params->get('domain', 'https://www.joomla.org');
?>

<a href="<?php echo $domain; ?>">
	<?php echo '[PROJECT_NAME]' . $test; ?>
</a>

Editing language/en-GB/en-GB.mod_foo.ini

Here we can specify the text for the English version of the field label.

MOD_FOO_FIELD_URL_LABEL="Url"

Completed language/en-GB/en-GB.mod_foo.ini

The complete language/en-GB/en-GB.mod_foo.ini file is as follows:

MOD_FOO="[PROJECT_NAME]"
MOD_FOO_XML_DESCRIPTION="Foo Module"
MOD_FOO_FIELD_URL_LABEL="Url"

Test your module

Now you can zip all files and install them via the Joomla Extension Manager. After that you can choose your module in the module manager, when you create a new site module.

In the backend, you will see your module like displayed in the next image.

In the basic tab, you will see the custom field where you can insert a domain. The text for the label is fetched from the language file.

Moduletutorial31-en.png

In the advanced tab, you will see all default options except the cache mode because of this is a hidden field.

Moduletutorial32-en.png

In the frontend, you will see your module like displayed in the next image. The text form your helper file is displayed and you should see a hyperlink.

Moduletutorial33-en.png

Conclusione

I campi del modulo offrono all'utente un modo semplice per personalizzare il modulo in base alle impostazioni dei siti. Questo permette di aumentare l'ambito dei moduli.

You can find boilerplates hereː

I file di esempio per questo Tutorial possono essere trovati all'indirizzo hereː

Vedere questo numero per eventuali cambiamenti futuri:


Use Install, Update and Uninstall script - Part 4

Requirements

You need Joomla! 4.x for this tutorial (as of writing currently Joomla! 4.0.0-alpha6-dev)

Scripts

Installing, updating and uninstalling a module may require additional operations that cannot be achieved by the basic operations described in the main XML file. Joomla offers a new approach to solve this problem. It consists in using a PHP script file containing a class using five methods:

  • preflight which is executed before install and update
  • install
  • update
  • uninstall
  • postflight which is executed after install and update

Let's take a look how to use them in Joomla 4. We use the helper file for this.

File Structure

We will create/change the following files:

  • script.php - This is the file we use here as an example. We have to create it.
  • language/en-GB/en-GB.mod_foo.sys.ini - In this file we will add text.
  • mod_foo.xml - We create a new file. This must be installed during the installation. For this we have to specify it in this file.

Creating script.php

Writing an extension script consists in declaring a class whose name is mod_ModuleNameInstallerScript with these 5 methods. See the comments in the file for more information. In this comments I explain when a method is called.

In this example, I only use text to show when which method will be executed. In addition, I show you how to check the minimum requirements. Of course you can do much more. For example, you can delete files that are no longer needed in a new version of your module. This can be seen in the file. Another idea for this file is to create sample content, to show a success message with the current installed version number or you can redirect after a successful installation to the page with the module settings.

Completed script.php

The complete script.php file is as follows:

<?php
/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */

// No direct access to this file
defined('_JEXEC') or die;

use Joomla\CMS\Language\Text;
use Joomla\CMS\Log\Log;

/**
 * Script file of Foo module
 */
class mod_fooInstallerScript {

    /**
     * Extension script constructor.
     *
     * @return  void
     */
    public function __construct() {
        $this->minimumJoomla = '4.0';
        $this->minimumPhp = JOOMLA_MINIMUM_PHP;
    }

    /**
     * Method to install the extension
     *
     * @param   InstallerAdapter  $parent  The class calling this method
     *
     * @return  boolean  True on success
     */
    function install($parent) {
        echo Text::_('MOD_FOO_INSTALLERSCRIPT_INSTALL');

        return true;
    }

    /**
     * Method to uninstall the extension
     *
     * @param   InstallerAdapter  $parent  The class calling this method
     *
     * @return  boolean  True on success
     */
    function uninstall($parent) {
        echo Text::_('MOD_FOO_INSTALLERSCRIPT_UNINSTALL');

        return true;
    }

    /**
     * Method to update the extension
     *
     * @param   InstallerAdapter  $parent  The class calling this method
     *
     * @return  boolean  True on success
     */
    function update($parent) {
        echo Text::_('MOD_FOO_INSTALLERSCRIPT_UPDATE');

        return true;
    }

    /**
     * Function called before extension installation/update/removal procedure commences
     *
     * @param   string            $type    The type of change (install, update or discover_install, not uninstall)
     * @param   InstallerAdapter  $parent  The class calling this method
     *
     * @return  boolean  True on success
     */
    function preflight($type, $parent) {
        // Check for the minimum PHP version before continuing
        if (!empty($this->minimumPhp) && version_compare(PHP_VERSION, $this->minimumPhp, '<')) {
            Log::add(Text::sprintf('JLIB_INSTALLER_MINIMUM_PHP', $this->minimumPhp), Log::WARNING, 'jerror');

            return false;
        }

        // Check for the minimum Joomla version before continuing
        if (!empty($this->minimumJoomla) && version_compare(JVERSION, $this->minimumJoomla, '<')) {
            Log::add(Text::sprintf('JLIB_INSTALLER_MINIMUM_JOOMLA', $this->minimumJoomla), Log::WARNING, 'jerror');

            return false;
        }
        
        echo Text::_('MOD_FOO_INSTALLERSCRIPT_PREFLIGHT');
        echo $this->minimumJoomla . ' ' . $this->minimumPhp;

        return true;
    }

    /**
     * Function called after extension installation/update/removal procedure commences
     *
     * @param   string            $type    The type of change (install, update or discover_install, not uninstall)
     * @param   InstallerAdapter  $parent  The class calling this method
     *
     * @return  boolean  True on success
     */
    function postflight($type, $parent) {
        echo Text::_('MOD_FOO_INSTALLERSCRIPT_POSTFLIGHT');

        return true;
    }
}

Editing language/en-GB/en-GB.mod_foo.sys.ini

There is not much to explain here. Write the text for the translation into this file.

Completed language/en-GB/en-GB.mod_foo.sys.ini file

The complete language/en-GB/en-GB.mod_foo.sys.ini file is as follows:

MOD_FOO="[PROJECT_NAME]"
MOD_FOO_XML_DESCRIPTION="Foo Module"
MOD_FOO_INSTALLERSCRIPT_PREFLIGHT="<p>Anything here happens before the installation/update/uninstallation of the module</p>"
MOD_FOO_INSTALLERSCRIPT_UPDATE="<p>The module has been updated</p>"
MOD_FOO_INSTALLERSCRIPT_UNINSTALL="<p>The module has been uninstalled</p>"
MOD_FOO_INSTALLERSCRIPT_INSTALL="<p>The module has been installed</p>"
MOD_FOO_INSTALLERSCRIPT_POSTFLIGHT="<p>Anything here happens after the installation/update/uninstallation of the module</p>"

Editing mod_foo.xml

You have to add a line, so that the script is called automatically in Joomla.

<scriptfile>script.php</scriptfile>

Completed mod_foo.xml

The complete mod_foo.xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="4.0" client="site" method="upgrade">
    <name>MOD_FOO</name>
    <creationDate>[DATE]</creationDate>
    <author>[AUTHOR]</author>
    <authorEmail>[AUTHOR_EMAIL]</authorEmail>
    <authorUrl>[AUTHOR_URL]</authorUrl>
    <copyright>[COPYRIGHT]</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <version>1.0</version>
    <description>MOD_FOO_XML_DESCRIPTION</description>
    <namespace>Joomla\Module\Foo</namespace>
    <scriptfile>script.php</scriptfile>
    <files>
        <filename module="mod_foo">mod_foo.php</filename>
        <folder>tmpl</folder>
        <folder>Helper</folder>
        <folder>language</folder>
        <filename>mod_foo.xml</filename>
    </files>
    <config>
        <fields name="params">
            <fieldset name="basic">
                <field
                    name="domain"
                    type="url"
                    label="MOD_FOO_FIELD_URL_LABEL"
                    filter="url"
                />
            </fieldset>
            <fieldset name="advanced">
                <field
                    name="layout"
                    type="modulelayout"
                    label="JFIELD_ALT_LAYOUT_LABEL"
                    class="custom-select"
                />
                <field
                    name="moduleclass_sfx"
                    type="textarea"
                    label="COM_MODULES_FIELD_MODULECLASS_SFX_LABEL"
                    rows="3"
                />
                <field
                    name="cache"
                    type="list"
                    label="COM_MODULES_FIELD_CACHING_LABEL"
                    default="0"
                >
                    <option value="1">JGLOBAL_USE_GLOBAL</option>
                    <option value="0">COM_MODULES_FIELD_VALUE_NOCACHING</option>
                </field>
                <field
                    name="cache_time"
                    type="number"
                    label="COM_MODULES_FIELD_CACHE_TIME_LABEL"
                    default="0"
                />
                <field
                    name="cachemode"
                    type="hidden"
                    default="itemid"
                >
                    <option value="itemid"></option>
                </field>
            </fieldset>
        </fields>
    </config>
</extension>

Test your module

Now you can zip all files and install them via the Joomla Extension Manager. Immediately after the installation, you will see the following information. This you had entered in the script so.

Moduletutorial14-en.png

Conclusion

As you can see, Joomla offers you a lot to make your extension easy to use - right from the start.

You can find boilerplates hereː

The sample files for this Tutorial can be found hereː


Use Joomla Updaterː Adding Auto Update - Part 5

Requirements

You need Joomla! 4.x for this tutorial (as of writing currently Joomla! 4.0.0-alpha6-dev)

Joomla Updater

The first thing to do is to read the Managing Component Upgrades with Joomla 2.5 - Part 1 tutorial to give an idea of how the upgrade process works in Joomlaǃ. Whilst written for 2.5 the process hasn't changed. Also read Deploying an update server - this is what we'll be implementing in this tutorial.

File Structure

We will create/change the following files:

  • mod_foo.xml - The only way to update our existing module is to add in a update server - for example http://www.example.com/foo_update.xml - into the xml file.
  • foo_update.xml - Then we have to create the XML file for the update server at http://www.example.com/foo_update.xml to let Joomla know an update is available.

Editing mod_foo.xml

To add our update server, we need to insert the following lines in your XML-Fileː

<updateservers>
    <server type="extension" priority="1" name="[PROJECT_NAME]">https://www.example.com/mod_foo.xml</server>
</updateservers>

Completed mod_foo.xml

The complete mod_foo.xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="4.0" client="site" method="upgrade">
    <name>MOD_FOO</name>
    <creationDate>[DATE]</creationDate>
    <author>[AUTHOR]</author>
    <authorEmail>[AUTHOR_EMAIL]</authorEmail>
    <authorUrl>[AUTHOR_URL]</authorUrl>
    <copyright>[COPYRIGHT]</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <version>1.0</version>
    <description>MOD_FOO_XML_DESCRIPTION</description>
    <namespace>Joomla\Module\Foo</namespace>
    <files>
        <filename module="mod_foo">mod_foo.php</filename>
        <folder>tmpl</folder>
        <folder>Helper</folder>
        <folder>language</folder>
        <filename>mod_foo.xml</filename>
    </files>
    <updateservers>
        <server type="extension" priority="1" name="[PROJECT_NAME]">https://www.example.com/mod_foo.xml</server>
    </updateservers>
    <config>
        <fields name="params">
            <fieldset name="basic">
                <field
                    name="domain"
                    type="url"
                    label="MOD_FOO_FIELD_URL_LABEL"
                    filter="url"
                />
            </fieldset>
            <fieldset name="advanced">
                <field
                    name="layout"
                    type="modulelayout"
                    label="JFIELD_ALT_LAYOUT_LABEL"
                    class="custom-select"
                />
                <field
                    name="moduleclass_sfx"
                    type="textarea"
                    label="COM_MODULES_FIELD_MODULECLASS_SFX_LABEL"
                    rows="3"
                />
                <field
                    name="cache"
                    type="list"
                    label="COM_MODULES_FIELD_CACHING_LABEL"
                    default="0"
                >
                    <option value="1">JGLOBAL_USE_GLOBAL</option>
                    <option value="0">COM_MODULES_FIELD_VALUE_NOCACHING</option>
                </field>
                <field
                    name="cache_time"
                    type="number"
                    label="COM_MODULES_FIELD_CACHE_TIME_LABEL"
                    default="0"
                />
                <field
                    name="cachemode"
                    type="hidden"
                    default="itemid"
                >
                    <option value="itemid"></option>
                </field>
            </fieldset>
        </fields>
    </config>
</extension>

So now that Joomlaǃ is searching for updates to our extension - let's create one to test out our process. But first we need to create the file foo_update.xml. So far we have only described the update server. We do not know yet if there is an update. In the file foo_update.xml we indicate when a new version is published and where it can be downloaded.

Creating foo_update.xml

Now we have to create the XML file at http://www.example.com/foo_update.xml to let Joomla know an update is available.

Completed foo_update.xml

The complete foo_update.xml file is as follows:

<?xml version="1.0" ?>
<updates>
    <update>
        <name>Foo</name>
        <description>This is mod_foo 1.0.1</description>
        <element>mod_foo</element>
        <type>module</type>
        <version>1.0.1</version>
        <downloads>
            <downloadurl type="full" format="zip">http://www.example.com/mod_foo_101.zip</downloadurl>
        </downloads>
        <maintainer>Joomla</maintainer>
        <maintainerurl>http://www.example.com</maintainerurl>
        <targetplatform name="joomla" version="4.0"/>
        <client>site</client>
    </update>
</updates>

After uploading this file to the address https://www.example.com/mod_foo.xml the update will be displayed in the Joomla backend.

Test your module update

Create a copy of the module as it is now. Then let's update the version number to 1.0.1. Now you can zip all files. After that you should load your zip to the URL http://www.example.com/mod_foo_101.zip. Now you can update your module via the Joomla Updater.

Commercial Modules

Note that in our files we have linked to the extensions updates xml file. And from that xml file we have a location for the zip of the module. This means that if someone was to track this backwards they could find the physical source of your modules zip file. If you don't do like this, you can find a solution in this PRː https://github.com/joomla/joomla-cms/pull/15185 .

Conclusion

With the Joomlaǃ updater, you can easily reach all users and tell them that there is a new version. Even the update itself is easy.

Each extension should use an update server. Especially for security reasons.

You can find boilerplates hereː

The sample files for this Tutorial can be found hereː