How to Create Joomla 4.x Plugin

Plugins are easily installed as a .zip file but a correctly formatted XML file must be included. The object-oriented way of writing plugins involves writing a subclass of CMSPlugin.

XML Installation File

The XML file similar to other Joomla XML installation files. You have to add the group="xyz" entry in the <extension> tag and the plugin="xyz" in the <filename> tag. This information tells Joomla into which folder to copy the file and to which group the plugin should be added.

PHP File

The object-oriented way of writing plugins involves writing a subclass of CMSPlugin. The CMSPlugin is a base class that implements the basic properties of plugins. In the methods, the following properties are available:

  • $this->params: the parameters set for this plugin by the administrator
  • $this->_name: the name of the plugin
  • $this->_type: the group (type) of the plugin
  • $this->db: the db object
  • $this->app: the application object

Joomla 4 implements the SubscriberInterface which is the major change from Joomla 1.5-3.x. Instead of the function name automatically being detected and being the same as the event name, this allows you to have custom function names. This allows to tell what plugins are implementing what functions and as parsing public methods in PHP code is slow gives a significant performance boost.

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

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

class Plg<PluginGroup><PluginName> extends CMSPlugin implements SubscriberInterface
{
/**
* Load the language file on instantiation
*/
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;
}
}
?>

 

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive