J4.x

Difference between revisions of "Creating a Simple Module/pl"

From Joomla! Documentation

(Created page with "=== Wymagania ===")
 
(3 intermediate revisions by the same user not shown)
Line 190: Line 190:
  
 
=== Wymagania ===
 
=== Wymagania ===
You need Joomla! 4.x for this tutorial (as of writing currently Joomla! 4.0.0-alpha6-dev)
+
Potrzebujesz aktualnej Joomli! 4.x dla tego samouczka (na dzień dzisiejszy Joomla! 4.0.0-alpha6-dev)
  
== Namespaces ==
+
== Przestrzenie nazw ==
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.  
+
Przestrzenie nazw pojawiły się wraz z PHP 5.3 niejako naturalnie. W innych językach programowania, przez długi czas były już używane. Te małe struktury pomagają  w utrzymywaniu przejrzystości naszego kodu.  
  
 
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.
 
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.

Latest revision as of 06:04, 10 January 2021

Other languages:
Deutsch • ‎Ελληνικά • ‎English • ‎français • ‎italiano • ‎Nederlands • ‎polski • ‎português
Joomla! 
4.x
>Samouczek
Tworzenie prostego modułu dla Joomla 4.x

Samouczek o tym jak stworzyć prosty moduł dla Joomla w wersji 4x.

Contents

Wprowadzenie

Joomlaǃ 4 proponuje pięć typów rozszerzeńː

  • Komponenty
    Komponent jest głównym elementem witryny. Zajmuje się przetwarzaniem danych, a także wprowadzaniem i przechowywaniem ich w bazie danych. Komponent w znacznej części witryn jest ich główną treścią.
  • Moduły
    Moduł jest dodatkiem do witryny, który rozszerza jej funkcjonalność. Moduł zazwyczaj jest drugorzędnym elementem strony i nie jest uważany za główną część jej funkcjonowania. Może on być widoczny w różnych pozycjach, można również zaznaczyć, na których aktywnych stronach menu ma być wyświetlany. Moduły są lekkimi i elastycznymi rozszerzeniami. Są one używane dla małych fragmentów witryny, które na ogół są mniej złożone i mogą być widoczne na różnych elementach.
  • Wtyczki
    Wtyczka operuje danymi wyjściowymi, które są już generowane przez system. Zazwyczaj nie jest ona uruchamiana jako oddzielna część witryny. Pobiera ona dane z innych źródeł (np. treści) i manipuluje tymi danymi przed ich wyświetleniem. Wtyczka zazwyczaj działa za kulisami.
  • Języki
    Język jest najprawdopodobniej najprostszym rozszerzeniem Joomla!. W zasadzie pliki pakietów językowych składają się z pary klucz/wartość, które zapewniają tłumaczenie statycznych ciągów tekstowych, przypisanych w kodzie źródłowym Joomla!
  • Szablony
    Szablon w zasadzie określa wygląd strony internetowej Joomla!

Joomla! 4 jest skonstruowana przy użyciu pięciu różnych aplikacji:

  • Instalacja (służy do instalacji Joomla, musi być usunięta po zakończeniu instalacji);
  • Administrator (backend - służy do zarządzania treścią);
  • Witryna (frontend - używany do wyświetlania treści);
  • CLI (używany do uzyskania dostępu do Joomli w wierszu poleceń i do zadań crona);
  • API (usługi internetowe - wykorzystywane do tworzenia interfejsów API dla treści dostępnych maszynowo);

Aplikacja instalacyjna jest używana raz. Administrator oraz witryna używane są poprzez zastosowanie komponentów wraz z modułami. Każdy moduł posiada pojedynczy punkt dostępu umieszczony w katalogu modules i analogicznie administrator/modules. Punkt ten nosi nazwę mod_nazwamodułu/mod_nazwamodułu.php (prefiks mod_ jest zapisem umownym). Punktem wejściowym dla modułu logowania jest dla przykładu /mod_login/mod_login.php.

Wymagania

Potrzebujesz pakietu instalacyjnego Joomla! 4.x dostępnego dla tego samouczka? (W tym miejscu pobierzesz najnowszą wersję).

Możesz również pobrać Joomla! 4 pod adresem GitHub, na Stronie deweloperskiej lub możesz stworzyć darmową stronę internetową pod adresem https://launch.joomla.org.


Tworzenie prostego modułu, rozwijanie modułu podstawowego - Część 1

W standardowej instalacji Joomla! można zobaczyć wiele przykładów modułów. Na przykład:

  • Menu
  • Najnowsze wiadomości
  • Formularz logowania
  • i wiele innych...

Ten samouczek wyjaśni jak stworzyć prosty moduł. Poznasz podstawową strukturę plików modułu Joomlaǃ 4. Ta podstawowa struktura może być następnie rozszerzona w celu stworzenia bardziej rozbudowanych modułów.

Struktura plików

Istnieje kilka podstawowych plików, które są wykorzystywane w standardowym schemacie tworzenia modułów:

  • mod_foo.php - plik ten jest głównym punktem wejściowym dla modułu. Będzie on wykonywał wszelkie niezbędne procedury inicjalizacyjne, procedury wywoływania helpera w celu zebrania wszelkich niezbędnych danych oraz będzie zawierał szablon, który wyświetli wyjście modułu.
  • mod_foo.xml - plik ten zawiera informacje o module. Określa on pliki, które muszą być zainstalowane przez instalator Joomla!, określa także parametry konfiguracyjne modułu.
  • tmpl/default.php - to jest szablon modułu. Plik ten pobierze dane zebrane przez mod_foo.php i wygeneruje HTML, który zostanie wyświetlony na stronie.
  • language/en-GB/mod_foo.ini oraz language/en-GB/mod_foo.sys.ini- są to pliki językowe, które zawierają tekst w języku angielskim.


Tworzenie mod_foo.php

Plik mod_foo.php będzie wykonywał następujące zadania:

  • Zaimportuje klasę ModuleHelper do bieżącego obszaru. Będziemy potrzebować jej później do wyświetlenia wyjścia.
  • Dołączy szablon do wyświetlania wyjścia.

Klasa ModuleHelper jest importowana do naszego bieżącego obszaru na początku pliku.

use Joomla\CMS\Helper\ModuleHelper;

Na końcu dołączamy szablon do wyświetlenia wyjścia poprzez

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

Kompletny plik mod_foo.php

Kompletny plik mod_foo.php wygląda następująco:

<?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'));

Uwagaː w Joomla 3x zazwyczaj używa się linii $moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));. Nie potrzebujesz już tego. Zobacz ten Pull-Requestː https://github.com/joomla/joomla-cms/pull/17447.

Linią, której do tej pory nie wyjaśniliśmy, jest pierwsza linia defined('_JEXEC') or die;. Linia sprawdza, czy plik ten jest dołączany z aplikacji Joomla. Jest to konieczne, aby zapobiec wstrzyknięciu zmiennej i innym potencjalnym problemom związanym z bezpieczeństwem.

Tworzenie tmpl/default.php

Plik default.php jest szablonem, który wyświetla wyjście modułu.

Kompletny plik tmpl/default.php

Kod w pliku tmpl/default.php wygląda następująco:

<?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]';

Ważną kwestią jest to, że plik szablonu ma taki sam zakres jak plik mod_foo.php. Oznacza to, że zmienna zdefiniowana w pliku mod_foo.php może być następnie użyta w pliku szablonu bez żadnych dodatkowych deklaracji czy wywołań funkcji.

Tworzenie mod_foo.xml

Plik mod_foo.xml jest plikiem instalacyjnym. Większość wpisów jest oczywista.

Kompletny plik mod_foo.xml

Kod w pliku mod_foo.xml wygląda następująco:

<?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>

Tworzenie plików językowych

Pliki language/en-GB/mod_foo.ini oraz language/en-GB/mod_foo.sys.ini są używane do tłumaczenia tekstu w witrynie i na zapleczu. Należy pamiętać, że struktura plików językowych została zaktualizowana w Joomla 4, a prefiksy językowe na poszczególnych plikach w folderze językowym nie są już wymagane.

Kod dla language/en-GB/mod_foo.sys.ini jest następujący:

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

Kod dla language/en-GB/mod_foo.ini jest następujący:

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

Plik .sys.ini jest używany do tłumaczenia opisu rozszerzenia podczas instalacji, podczas gdy plik .ini jest używany do tłumaczenia pozostałych łańcuchów i opisu podczas korzystania z Twojego rozszerzenia.

Więcej informacji na temat plików językowych można znaleźć w tym miejscu.


Przetestuj swój moduł

Teraz możesz spakować wszystkie pliki i zainstalować je za pomocą Joomla Extension Manager.
Następnie wybierz swój moduł w menedżerze modułów, oraz wyświetl na jakich stronach ma się wyświetlać.

Moduletutorial1-en.png
Moduletutorial2-en.png

Na następnym obrazku możesz zobaczyć jak powinien wyglądać utworzony przez Ciebie moduł na wybranej stronie.

Moduletutorial3-en.png

Wniosek

Opracowanie prostego modułu dla Joomli jest dość łatwym procesem. Przy użyciu technik opisanych w tym samouczku można bez trudu opracować nieskończoną ilość modułów.

Schematy kodu możesz znaleźć w tym miejscu:

Przykładowe pliki tego samouczka można znaleźć na stronie w tym miejscuː.


Dodanie klasy pomocniczej przy użyciu przestrzeni nazw - Część 2

Wymagania

Potrzebujesz aktualnej Joomli! 4.x dla tego samouczka (na dzień dzisiejszy Joomla! 4.0.0-alpha6-dev)

Przestrzenie nazw

Przestrzenie nazw pojawiły się wraz z PHP 5.3 niejako naturalnie. W innych językach programowania, przez długi czas były już używane. Te małe struktury pomagają w utrzymywaniu przejrzystości naszego kodu.

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>

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. The text from your helper file is displayed.

Moduletutorial23-en.png

Conclusion

As you can see, once you get a bit into the namespaces, they are not that complicated anymore. In big projects they can bring a lot of benefits. However, we should plan namespaces, as otherwise it will soon be more time-consuming.

You can find boilerplates hereː

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

Conclusion

Form fields give the user an easy way to customize the module to their sites settings. This allows the modules scope to be increased.

You can find boilerplates hereː

The sample files for this Tutorial can be found hereː

See this issue for possible future changes:


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_UNINSTALL');

        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ː