Work In Progress

This book is currently work in progress. Some sections are not yet written. Thank you for your understanding!

Using your extension class from outside the component

Now we are finally able to answer the question which you had in mind coming to this section: why in the name of Cthulu do I have to have an extension class and what does it accomplish beyond adding yet another layer of complexity to my extension writing problems?

For that, let's consider this. Let's say we have a news site and we are building a system plugin which checks every day for newly published articles, auto-generating a daily summary blog post using the intro text of these articles and some preset template (maybe even some judicious use of a GPT-3–based AI). This plugin would need to publish an article. You could of course just instantiate the ArticleTable class of com_content directly to do that but this would not run any content plugins or create the right entries in the #__assets table, breaking your site. You need to use the com_content Article backend model of com_content.

Back in the Joomla 3 days you would do that by directly instantiating the ContentModelArticle class. Okay, first problem: Joomla didn't know where to find it so you have to require_once() the file. Second problem: what if that model changes over time and has dependencies to other classes you have failed to require the files of? Believe me, I've been there, done that and it was about as enjoyable as using a rusty fork to pull my eyes out of their sockets.

In Joomla 4 you don't have to care about the class autoloading, but the ArticleModel will actually need access to other services provided by the com_content component for things like tagging, custom fields and workflows. If you try to instantiate the model class directly you will get a lot of errors as well. So, who are you gonna call? No, not Ghostbusters; they are Hollywood fiction. You're gonna call the very real and very useful bootComponent method of the application!

$contentExtension = \Joomla\CMS\Factory::getApplication()
  ->bootComponent('com_content');
$articleModel = $contentExtension
  ->getMVCFactory()
  ->createModel('Article', 'Administrator');

The first two lines told Joomla to “boot” the com_content component, returning its extension object. Now we have have access to all services known to this object through its various getters (method whose name start with get).

This works for any component, anywhere, anytime. You can be in the frontend, backend, API application or CLI application or in an execution context you don't care to know about in a Scheduled Tasks plugin. No problem! You can boot any components — yours, core, or third party — to get its extension object and Bob's your uncle.