Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Development and Security

Plugins and Events

Learn how Joomla plugins hook into the request lifecycle: plugin groups, key events, a modern Joomla 5 plugin with SubscriberInterface, and a runnable PHP event stand-in.

A plugin is a piece of code that Joomla calls at defined moments, called events. When an article is about to be shown, when a user logs in, when the page head is built, Joomla announces the event and every enabled plugin listening to it runs. Plugins need no menu item and no page: they change or extend behavior from the inside, which is why captchas, editors, redirect handling, SEO tags and login methods are all plugins.

Joomla cannot run on this site. The Joomla code below is read-only, and the TryIt blocks are plain PHP stand-ins that implement the same observer idea so you can run and change it.

Plugin groups

Plugins are organized in groups. The group decides which events the plugin may subscribe to and when Joomla loads it:

Group Typical job
system Runs on every request: caching, SEF, redirect, language filter
content Reacts when content is prepared or saved: shortcodes, emailing, pagination
user Reacts to user actions: login, profile, registration
authentication Checks credentials (database login, LDAP)
editors, editors-xtd The WYSIWYG editor and its buttons
captcha, multifactorauth Spam protection and second factors
finder Search index sources for Smart Search
privacy Personal data export and removal
task Jobs for the Task Scheduler (Joomla 4.1 and later)
webservices Registers API routes

Manage them under System > Plugins, where you can enable, disable and filter by group. Plugins appear in alphabetical order by default; the order inside a group can matter, and you can reorder them.

The request lifecycle and its events

Some of the best known events, in order of a normal page request:

  1. onAfterInitialise: the application started. Good for early checks.
  2. onAfterRoute: Joomla has decided which component and menu item belong to the URL.
  3. onAfterDispatch: the component has produced its output.
  4. onBeforeCompileHead: last chance to add meta tags, scripts or styles to the head.
  5. onBeforeRender and onAfterRender: around the final HTML; onAfterRender can modify the whole HTML string.

Content events: onContentPrepare (before an article is displayed, to transform text), onContentBeforeSave, onContentAfterSave, onContentBeforeDelete. User events: onUserLogin, onUserLogout, onUserBeforeSave, onUserAfterSave. Third-party extensions can define their own events and trigger them too.

flowchart LR
    A["onAfterInitialise"] --> B["onAfterRoute"]
    B --> C["Component runs"]
    C --> D["onAfterDispatch"]
    D --> E["onBeforeCompileHead"]
    E --> F["Render template"]
    F --> G["onAfterRender"]

Plugins listen at these points; each can inspect or change what passes through.

A modern plugin (Joomla 4.x and 5)

A content plugin that replaces the text in articles has three files. The manifest greeting.xml:

XML
<extension type="plugin" group="content" method="upgrade">
    <name>plg_content_greeting</name>
    <version>1.0.0</version>
    <namespace path="src">Example\Plugin\Content\Greeting</namespace>
    <files>
        <folder plugin="greeting">services</folder>
        <folder>src</folder>
    </files>
</extension>

The service provider services/provider.php:

PHP
<?php
\defined('_JEXEC') or die;

use Example\Plugin\Content\Greeting\Extension\Greeting;
use Joomla\CMS\Extension\PluginInterface;
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\DI\Container;
use Joomla\DI\ServiceProviderInterface;
use Joomla\Event\DispatcherInterface;

return new class () implements ServiceProviderInterface {
    public function register(Container $container): void
    {
        $container->set(PluginInterface::class, function (Container $container) {
            $plugin = new Greeting(
                $container->get(DispatcherInterface::class),
                (array) PluginHelper::getPlugin('content', 'greeting')
            );
            $plugin->setApplication(Factory::getApplication());
            return $plugin;
        });
    }
};

And the plugin class src/Extension/Greeting.php, which subscribes to an event with SubscriberInterface:

PHP
<?php
namespace Example\Plugin\Content\Greeting\Extension;

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

\defined('_JEXEC') or die;

final class Greeting extends CMSPlugin implements SubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return ['onContentPrepare' => 'replaceGreeting'];
    }

    public function replaceGreeting(ContentPrepareEvent $event): void
    {
        $item = $event->getItem();
        if (isset($item->text)) {
            $item->text = str_replace('{greeting}', 'Hello, visitor!', $item->text);
        }
    }
}

The event arguments differ between major versions (Joomla 4 used onContentPrepare($context, &$article, &$params, $page) with plain arguments, Joomla 5 passes event objects), so check the documentation for the version you target. The pattern of "declare events in getSubscribedEvents, implement a method per event" is the one to keep.

A plugin can also read parameters from its XML <config> block, for example a configurable greeting text, through $this->params->get('text', 'Hello'). Plugin settings appear in the admin automatically.

Simulating events in plain PHP

The observer pattern behind plugins is simple: a dispatcher keeps a list of listeners per event name, and trigger calls them in order. This stand-in includes priorities and lets a listener modify the data.

PHP A mini event dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The order matters: the uppercase step runs after the replacement because its priority is lower. In Joomla you control ordering through the plugin order in the admin and through event priorities.

Another classic: the head and render events

A system plugin often adds a meta tag or scans the final HTML. This stand-in mimics onAfterRender by modifying an HTML string, here adding rel="noopener" to external links.

PHP Post-process the page like onAfterRender

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Regex on HTML is fragile; real plugins prefer the DOM or Joomla's document API where possible. This is a demonstration of the hook, not a model of good HTML parsing.

Good plugin habits

  • Do one job. A plugin that changes ten things is hard to debug.
  • Be cheap. System plugins run on every request, so avoid database queries and heavy work in them; check the context first and return early.
  • Check the context. onContentPrepare runs for articles, categories, modules and more; test $event->getContext() before touching the item.
  • Fail safely. Never throw on a harmless condition; log it with Joomla's Log instead.
  • Respect security. Escape output and validate input as shown in the database and input lesson.
  • Disable, do not delete, when diagnosing. Turning plugins off one at a time is the quickest way to find which one breaks a page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a Joomla event?

    Events like onAfterRender or onUserLogin are triggered by the core or extensions; listening plugins run.
  2. 2. Which plugin group runs on every request?

    System plugins load for every request, so keep them lightweight.
  3. 3. In a modern Joomla plugin, where do you declare which events it handles?

    SubscriberInterface::getSubscribedEvents() returns the event-to-method map.
  4. 4. Why check the context inside onContentPrepare?

    Without a context check your code may run on modules and other content unexpectedly.

Summary

  • Plugins react to events; groups decide which events apply and when they load.
  • Key events: onAfterInitialise, onAfterRoute, onAfterDispatch, onBeforeCompileHead, onAfterRender, onContentPrepare, onUserLogin and more.
  • A modern plugin has a manifest, a service provider and a class implementing SubscriberInterface.
  • Event arguments differ between Joomla versions; read the docs for your target.
  • Keep plugins small, cheap, context-aware and secure.

Next: The Database API and Input Filtering