J4.x

Difference between revisions of "Creating a Plugin for Joomla/it"

From Joomla! Documentation

(Created page with "=== Usare i plugin nel tuo codice ===")
(Created page with "Se stai creando un plug-in per un nuovo evento non principale, ricorda di attivare il plug-in dopo averlo installato. Precedi qualsiasi riferimento al tuo nuovo plugin con il<...")
Line 147: Line 147:
  
 
=== Usare i plugin nel tuo codice ===
 
=== Usare i plugin nel tuo codice ===
If you are creating a plugin for a new, non-core event, remember to activate your plugin after you install it. Precede any reference to your new plugin with the <tt>JPluginHelper::importPlugin()</tt> command.
+
Se stai creando un plug-in per un nuovo evento non principale, ricorda di attivare il plug-in dopo averlo installato. Precedi qualsiasi riferimento al tuo nuovo plugin con il<tt>JPluginHelper::importPlugin()</tt>.
  
 
Now that you've created your plugin, you will probably want to call it in your code. You might not: the Joomla core has a number of built-in events that you might want your plugin code to be registered to (and in that case you can ignore this section).
 
Now that you've created your plugin, you will probably want to call it in your code. You might not: the Joomla core has a number of built-in events that you might want your plugin code to be registered to (and in that case you can ignore this section).

Revision as of 05:36, 23 January 2022

Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Nederlands • ‎Türkçe • ‎español • ‎français • ‎italiano • ‎português do Brasil • ‎русский • ‎فارسی • ‎中文(台灣)‎
Tutorial
Come creare un plugin per Joomla 4
Joomla! 
4.x
series

La struttura del plugin per Joomla! 1.5, 2.5 e 3.x era molto flessibile e potente. Non solo i plug-in possono essere utilizzati per gestire gli eventi attivati dall'applicazione principale e dalle estensioni, ma i plug-in possono anche essere utilizzati per rendere estensibili e potenti estensioni di terze parti. In Joomla 4.x abbiamo riscritto molto del sistema di dispatcher per aumentare ulteriormente la flessibilità quando si modificano i parametri passati come eventi aumentando contemporaneamente le prestazioni dei plugin.

Questo How-To dovrebbe fornirti le basi di ciò che devi sapere per sviluppare il tuo plugin. La maggior parte dei plugin consiste in un solo file di codice, ma per installare correttamente il codice del plugin deve essere impacchettato in un file di installazione che può essere elaborato dal programma di installazione di Joomla.

Creazione del file di installazione

Come per tutte le estensioni in Joomla, i plugin sono facilmente installabili come file .zip (è supportato anche .tar.gz) ma deve essere incluso un file XML formattato correttamente.
Ad esempio, ecco il file di installazione XML per il plugin di ricerca per categorie:

<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="search" method="upgrade">
	<name>plg_search_categories</name>
	<author>Joomla! Project</author>
	<creationDate>November 2005</creationDate>
	<copyright>Copyright (C) 2005 - 2018 Open Source Matters. All rights reserved.</copyright>
	<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
	<authorEmail>admin@joomla.org</authorEmail>
	<authorUrl>www.joomla.org</authorUrl>
	<version>3.0.0</version>
	<description>PLG_SEARCH_CATEGORIES_XML_DESCRIPTION</description>
	<files>
		<filename plugin="categories">categories.php</filename>
	</files>
	<languages>
		<language tag="en-GB">en-GB.plg_search_categories.ini</language>
		<language tag="en-GB">en-GB.plg_search_categories.sys.ini</language>
	</languages>
	<config>
		<fields name="params">

			<fieldset name="basic">
				<field
					name="search_limit"
					type="number"
					label="JFIELD_PLG_SEARCH_SEARCHLIMIT_LABEL"
					default="50"
				/>

				<field
					name="search_content"
					type="radio"
					label="JFIELD_PLG_SEARCH_ALL_LABEL"
					layout="joomla.form.field.radio.switcher"
					default="0"
					>
					<option value="1">JYES</option>
					<option value="0">JNO</option>
				</field>

				<field
					name="search_archived"
					type="radio"
					label="JFIELD_PLG_SEARCH_ARCHIVED_LABEL"
					layout="joomla.form.field.radio.switcher"
					default="0"
					>
					<option value="1">JYES</option>
					<option value="0">JNO</option>
				</field>
			</fieldset>

		</fields>
	</config>
</extension>

Come puoi vedere, il sistema è simile ad altri file di installazione XML di Joomla. Devi solo cercare la voce group="xxx" nel tag <extension> e le informazioni estese nel tag <filename> . Queste informazioni indicano a Joomla in quale cartella copiare il file e in quale gruppo deve essere aggiunto il plugin

Se stai creando un plug-in che risponda agli eventi principali esistenti, l'attributo group="xxx" verrebbe modificato per riflettere il nome della cartella del plug-in esistente per il tipo di evento che desideri aumentare. ad es. group="authentication" o group="user". Vedi Plugin/Events per un elenco completo delle categorie di eventi principali esistenti. Nella creazione di un nuovo plug-in per rispondere agli eventi principali, è importante che il nome del tuo plug-in sia univoco e non sia in conflitto con nessuno degli altri plug-in che potrebbero rispondere anche all'evento principale che desideri servire.

Se stai creando un plug-in per rispondere a eventi di sistema non principali, la tua scelta per il tag group="xxx" dovrebbe essere diversa da qualsiasi delle categorie principali esistenti.

SUGGERIMENTO: se aggiungi l'attributo method="upgrade" al tag extension, questo plugin può essere installato senza disinstallare una versione precedente. Tutti i file esistenti verranno sovrascritti, ma i vecchi file non verranno eliminati.


Creazione del plug-in

In Joomla 4 puoi anche avere il codice namespace nel tuo plugin - leggi Namespace Conventions in Joomla 4. Nota che il file della voce principale non ha uno spazio dei nomi, ma i campi e qualsiasi altro codice di supporto lo sono

Il modo object-oriented di scrivere i plug-in prevede la scrittura di una sottoclasse di CMSPlugin, una classe base che implementa le proprietà di base dei plug-in. Nei tuoi metodi sono disponibili le seguenti proprietà:

  • $this->params: i parameters impostati per questo plugin dall'amministratore
  • $this->_name: il nome del plugin
  • $this->_type: il gruppo (tipo) del plugin
  • $this->db: l'oggetto db
  • $this->app: l'oggetto dell'applicazione

SUGGERIMENTO: per utilizzare $this->db e $this->app, CMSPlugin verifica se la proprietà esiste e non è privata. Se si desidera utilizzare gli oggetti predefiniti, creare proprietà non istanziate nella classe del plugin (ad es. protected $db; protected $app; nella stessa area di protected $autoloadLanguage = true;). Le proprietà non esisteranno se non esplicitamente create.

Nell'esempio di codice seguente, <PluginGroup> che rappresenta il gruppo (type) del plug-in e <PluginName> rappresenta il nome. Nota che i nomi delle classi e delle funzioni in PHP non fanno distinzione tra maiuscole e minuscole.

Qui implementiamo anche SubscriberInterface che è il cambiamento principale rispetto a Joomla 1.5-3.x. Invece di rilevare automaticamente il nome della funzione e coincidere con il nome dell'evento, ciò consente di avere nomi di funzione personalizzati. Questo ci consente di dire quali plug-in stanno implementando quali funzioni e poiché l'analisi dei metodi pubblici nel codice PHP è lenta, offre un notevole aumento delle prestazioni

Nota in tutta la serie Joomla 4 esiste un livello deprecato che coprirà i plug-in che utilizzano la vecchia strategia di denominazione dei nomi dei plug-in che sono gli stessi del nome dell'evento quando SubscriberInterface non è implementato

<?php
// no direct access
defined( '_JEXEC' ) or die;

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\Event\Event;
use Joomla\Event\SubscriberInterface;

class Plg<PluginGroup><PluginName> extends CMSPlugin implements SubscriberInterface
{
	/**
	 * Load the language file on instantiation
	 *
	 * @var    boolean
	 * @since  3.1
	 */
	protected $autoloadLanguage = true;

	/**
	 * Returns an array of events this subscriber will listen to.
	 *
	 * @return  array
	 */
	public static function getSubscribedEvents(): array
	{
		return [
			'<EventName>' => 'myFunctionName',
		];
	}

	/**
	 * Plugin method is the array value in the getSubscribedEvents method
	 * The plugin then modifies the Event object (if it's not immutable)
	 */
	 public function myFunctionName(Event $event)
	 {
		/*
		 * Plugin code goes here.
		 * You can access parameters via $this->params
		 */
		return true;
	}
}
?>


Usare i plugin nel tuo codice

Se stai creando un plug-in per un nuovo evento non principale, ricorda di attivare il plug-in dopo averlo installato. Precedi qualsiasi riferimento al tuo nuovo plugin con ilJPluginHelper::importPlugin().

Now that you've created your plugin, you will probably want to call it in your code. You might not: the Joomla core has a number of built-in events that you might want your plugin code to be registered to (and in that case you can ignore this section).

New Joomla 4 Way

The new way of doing this in Joomla 4 is to get the dispatcher and dispatch a named event.

use Joomla\CMS\Event\AbstractEvent;
use Joomla\CMS\Factory;

$dispatcher = Factory::getApplication()->getDispatcher();

// Here we create an event however as long as you implement EventInterface you can create your own 
// custom classes
$event = AbstractEvent::create(
	'<EventName>',
	[
		'name' => $value,
	]
);

$eventResult = $dispatcher->dispatch('<EventName>', $event);

If you want to allow the user to modify values you can then use the event result and getResults back out of it. You can look at

defined('_JEXEC') or die;

use BadMethodCallException;
use Joomla\CMS\Event\AbstractImmutableEvent;
use Joomla\CMS\Table\TableInterface;

/**
 * Event class for an event
 */
class MyCustomEvent extends AbstractImmutableEvent
{
	/**
	 * Constructor.
	 *
	 * @param   string  $name       The event name.
	 * @param   array   $arguments  The event arguments.
	 *
	 * @throws  BadMethodCallException
	 */
	public function __construct($name, array $arguments = array())
	{
		if (!array_key_exists('myProperty', $arguments))
		{
			throw new BadMethodCallException("Argument 'myProperty' is required for event $name");
		}

		parent::__construct($name, $arguments);
	}

	/**
	 * Setter for the myProperty argument
	 *
	 * @param   mixed  $value  The value to set
	 *
	 * @return  mixed
	 *
	 * @throws  BadMethodCallException  if the argument is not of the expected type
	 */
	protected function setMyProperty($value)
	{
		if (!empty($value) && !is_object($value) && !is_array($value))
		{
			throw new BadMethodCallException("Argument 'src' of event {$this->name} must be empty, object or array");
		}

		return $value;
	}
}

Why have we introduced this name class over parameters? Well it makes it easier to introduce custom setters and getters for properties - currently a plugin can either completely change a property as it wants - for a components there's no way of imposing any limitations. Additionally it makes it much easier for developers to add and remove parameters in an event without having major b/c issues (as you are now calling defined methods and are not subject to a property being the 2nd argument of your function).

How to achieve maximum compatibility with Joomla 3

If you want to trigger an event in a similar way to the removed J3.x JEventDispatcher then you use code like this:

$results = \Joomla\CMS\Factory::getApplication()->triggerEvent( '<EventName>', <ParameterArray> );

It is important to note that the parameters have to be in an array. The plugin function itself will get the parameters as an Event object if it implements the SubscriberInterface and as individual values if it does not, but this method will always return an array that the plugin returns.

Note that if ANY plugin in a group doesn't implement the SubscriberInterface then the result property (as both a named parameter and result from a plugin) is used as a special property and cannot be used.