The plugin class has not changed in any significant manner apart from the fact that it can now be namespaced
and have any name you please as we learned in the previous two sections. It still extends from
\Joomla\CMS\Plugin\CMSPlugin
or one of its subclasses.
The biggest difference is that since Joomla 4.0 you can implement
the \Joomla\Event\SubscriberInterface
in your plugin class to handle modern events
instead of registering plugin event callbacks, as we already discussed.
The other big change starting with Joomla 4.2 is that you no longer need to declare an $app
property to magically get access to the Joomla application object or a $db
property to magically get
access to the database driver object. Instead, you need to set up these features through your service
provider.
![]() | Note |
---|---|
While you can still use the two properties, doing so will trigger a PHP deprecated notice. Unfortunately, if you want to support earlier Joomla versions (e.g. 3.x, 4.0 and 4.1) this is all you can do. |
Accessing the Joomla application object
Modify your provider's return line to read something like the following:
// Create the plugin $plugin = Example($subject, $config); // Push the application object $plugin->setApplication(\Joomla\CMS\Factory::getApplication()); return $plugin;
In your plugin's code you can now get the Joomla application object by doing
$app = $this->getApplication();
Accessing the Joomla database driver object
Accessing the Joomla database driver object is slightly more complicated.
First of all, your plugin class must have the \Joomla\Database\DatabaseAwareInterface
in its implements list and use the \Joomla\Database\DatabaseAwareTrait
. For example:
class Example extends \Joomla\CMS\Plugin\CMSPlugin implements \Joomla\Database\DatabaseAwareInterface { use \Joomla\Database\DatabaseAwareTrait; // The rest of the plugin class goes here. }
Your service provider must have the following line before the return $plugin;
line:
$plugin->setDatabase($container->get('DatabaseDriver'));
Inside your plugin's class you can now access the database driver object like this:
$db = $this->getDatabase();