Joomla injects a database, a form factory and a handful of other tools into your controllers, models and views. Those tools are first put into the MVCFactory, which hands them over to your MVC objects. But what if your model needs some other tool that is not provided by the core? In this article I’ll show you how it was done up to Joomla 6.1, the new way in Joomla 6.2, and a proposal for 6.3 that lets Joomla do all the wiring.
What you need is a custom MVCFactory. All objects that you want to inject into your MVC objects, both the ones that Joomla now provides in core and the new ones that are specific for your own component, are first put into the new MVCFactory and from there injected into your models, views, controllers or table-objects. Your custom MVCFactory is a pass-through for all dependencies, including the new ones.
A model that needs exchange rates
Say, you have a shop component that shows prices in the visitor's own currency. Its product model needs today's exchange rates. We put that knowledge in a service of its own, behind an interface:
interface ExchangeRatesInterface
{
public function getRate(string $from, string $to): float;
}
The real implementation, EcbExchangeRates, fetches the daily reference rates of the European Central Bank with Joomla's HTTP client. In a unit test you can use a fake, for instance always answering 1.10. The model only knows the interface, so it does not care which one it gets.
The model doesn’t instantiate that service by itself with new EcbExchangeRates(). That would tie the model to one implementation, and it would be difficult to use the fake instead of the real implementation. The clean way is dependency injection: the service is created somewhere else and handed to the model. The model only says what it needs.
In a Joomla component, that "somewhere else" is the MVCFactory. It is the object that creates your controllers, models, views, and table-objects (the MVC objects). Before handing them over, it equips them with the tools Joomla thinks they need: a database, a form factory, an event dispatcher, a user factory and more. Those tools come from the component's dependency injection (DI) container: a box in which each service is registered.
The standard MVCFactory only knows Joomla's own list of dependencies to inject. Our service is not on it; it is not even in the container. So first you register it in your component's container.
$container->share(
ExchangeRatesInterface::class,
fn (Container $container) => new EcbExchangeRates(HttpFactory::getHttp())
);
The share() method means: build it once, then hand out that same object every time I ask for it.
In the container you store it under the key of the interface name. The value is a recipe that produces the implementation. Switching to another rates-provider is a change in this one place.
We put the ExchangeRates-object into our custom MVCFactory, which hands that service to the MVC objects that need it. How this process of handing over the dependencies is done, has evolved in Joomla 6.2. And there are concrete plans to make it even simpler in Joomla 6.3. But first I’ll show you how it was done up to Joomla 6.1.
Up to Joomla 6.1: rewrite the service provider
Until recently there were three parts needed to get a service into a model.
Part 1: an aware-interface on the model
First the model has to say what it needs. In PHP, a class can promise to have certain methods by implementing an interface. An aware-interface is a tiny interface with just one public setter method. By implementing it, the model declares: "I know about exchange rates; hand them to me through setExchangeRates()." You can see it as a label on the class.
interface ExchangeRatesAwareInterface
{
public function setExchangeRates(ExchangeRatesInterface $rates): void;
}
class ProductModel extends ItemModel implements ExchangeRatesAwareInterface
{
private ExchangeRatesInterface $rates;
public function setExchangeRates(ExchangeRatesInterface $rates): void
{
$this->rates = $rates;
}
public function getPriceIn(float $priceInEuro, string $currency): float
{
return $priceInEuro * $this->rates->getRate('EUR', $currency);
}
}
Two things happen here. The words implements ExchangeRatesAwareInterface are the label. And because of that label, you know the model has a setExchangeRates() method.
Part 2: a factory that checks the interface
An MVCFactory creates the model, and reads the label. If the model implements the ExchangeRatesAwareInterface, then it sets the ExchangeRates-object into that model. In this example ShopMVCFactory extends Joomla's MVCFactory:
final class ShopMVCFactory extends MVCFactory
{
private ExchangeRatesInterface $rates; // filled via a setter
public function createModel($name, $prefix = '', array $config = [])
{
$model = parent::createModel($name, $prefix, $config);
if ($model instanceof ExchangeRatesAwareInterface) {
$model->setExchangeRates($this->rates);
}
return $model;
}
// createController() and createView() can do the same
}
Step by step, this is what happens when the component asks for the Product model:
parent::createModel()lets Joomla's own factory do the normal work: find the ProductModel class, create the object and give it the database and the other core tools.$model instanceof ExchangeRatesAwareInterfacereads the label: does this object implement that interface? For our ProductModel the answer is yes. For a model without the label it is no, and nothing happens.- If yes, the factory calls
setExchangeRates()with the concrete ExchangeRates service it holds. It knows that method exists, because the interface promised it. - The model, with its dependencies set, is returned to the caller, ready to use.
Joomla's standard MVCFactory works exactly like this for its own tools: a model that implements DatabaseAwareInterface gets setDatabase() called, and so on. You only add what is new. And because your factory is the MVCFactory, every controller it creates gets your factory too. When that controller later asks for a model, your custom createModel() runs.
Part 3: the service provider
This one you have to rewrite. A service provider is the class that puts a recipe into the container. Joomla's Joomla\CMS\Extension\Service\Provider\MVCFactory holds the recipe for the MVCFactory. But you cannot extend it: the namespace property is private, and the recipe itself is an anonymous function, written inline in register(). So you have to rewrite the whole service provider for your custom MVCFactory. Here is the inner part:
$container->set(
MVCFactoryInterface::class,
function (Container $container) {
$factory = new ShopMVCFactory('\\Acme\\Component\\Shop');
// Copied from the core service provider for the MVCFactory.
$factory->setFormFactory($container->get(FormFactoryInterface::class));
$factory->setDispatcher($container->get(DispatcherInterface::class));
$factory->setDatabase($container->get(DatabaseInterface::class));
$factory->setSiteRouter($container->get(SiteRouter::class));
$factory->setCacheControllerFactory($container->get(CacheControllerFactoryInterface::class));
$factory->setUserFactory($container->get(UserFactoryInterface::class));
$factory->setMailerFactory($container->get(MailerFactoryInterface::class));
// Add your custom service.
$factory->setExchangeRates($container->get(ExchangeRatesInterface::class));
return $factory;
}
);
The core MVCFactory service provider also instantiates a special ApiMVCFactory for the web services API. I left it out here, but if your component has a web services API, then you must also copy that part.

Joomla 6.2: an extendable service provider
The complaint that you have to rewrite part of the core code is not new. In August 2022, Nicholas Dionysopoulos opened issue #38555 pointing at this. Joomla 6.2 fixes that. PR #47718 by Tuan Pham Ngoc, "Refactor MVCFactory service provider to make it easier to extend", makes the core MVCFactory service provider extendable.
In his PR Tuan added three overridable methods to the core MVCFactory service provider:
getNamespace()gives you the component namespace that used to be locked away.createMVCFactory()decides which factory class is created. Override it to return your own.injectServicesIntoFactory($factory, $container)hands the services to the factory. Override it, call the parent for Joomla's list, then add yours.
As a bonus, the core now checks each label before using it (if ($factory instanceof DatabaseAwareInterface) and so on).
Part 1 stays as it was. Part 2 is almost the same, but implements the ExchangeRatesAwareInterface on the ShopMVCFactory, so it has a setExchangeRates() method. Part 3 shrinks from a copied recipe to a small child class:
use Joomla\CMS\Extension\Service\Provider\MVCFactory as MVCFactoryProvider;
final class ShopMVCFactoryProvider extends MVCFactoryProvider
{
protected function createMVCFactory(): MVCFactoryInterface
{
return new ShopMVCFactory($this->getNamespace());
}
protected function injectServicesIntoFactory(MVCFactoryInterface $factory, Container $container): void
{
parent::injectServicesIntoFactory($factory, $container); // Joomla's own list
if ($factory instanceof ExchangeRatesAwareInterface) {
$factory->setExchangeRates($container->get(ExchangeRatesInterface::class));
}
}
}
In services/provider.php of your component it is one line again:
$container->registerServiceProvider(new ShopMVCFactoryProvider('\\Acme\\Component\\Shop'));
Note the factory now wears the same ExchangeRatesAwareInterface label as the model. The easiest way to do that is to make an ExchangeRatesAwareTrait and use that in both the factory and the model. No copied lines are left. When a later Joomla version adds a service to its list, your factory gets it for free. One thing to remember: if you override createMVCFactory(), you also have to create an ApiMVCFactory if your component offers web services. Look at the core createMVCFactory() method how to do that.

Lazy: build it only when it is used
Using share() or set() to put an object in the container is the classical way. The container builds EcbExchangeRates as soon as it builds the factory, and an HTTP client with it. That happens whether the page shows a price or not, and a component boots on many pages where it does nothing at all.
The DI-container can postpone that work. Wrap the recipe in lazy():
$container->share(
ExchangeRatesInterface::class,
$container->lazy(
EcbExchangeRates::class,
fn (Container $container) => new EcbExchangeRates(HttpFactory::getHttp())
)
);
Now the container hands out a stand-in, a lazy proxy. It looks exactly like an EcbExchangeRates, but it only builds the real one the first time a method is called on it. Note that lazy() needs the concrete class, not the interface: PHP makes the stand-in from a real class. The factory, the setter and the model stay exactly the same; only the recipe changed. Nicholas asked for this kind of lazy loading back in 2022.
lazy() exists since version 3.1.0 of the Joomla DI package; Joomla 6 ships version 4. It relies on the lazy objects that arrived in PHP 8.4. On older PHP versions it simply builds the object straight away. Since Joomla 6.1, the core loads all its plugins this way (PR #46862).
The road not taken: a wrapper around the factory
Joomla 6.2 lets you extend the service provider. In 2022, Nicholas tried a different route: leave the provider alone and wrap the factory (plus a setMVCFactory() method on controllers). A wrapper (or "decorator") is an object that stands around another object with the same interface. Your class does not extend MVCFactory. It holds Joomla's factory inside, passes every call through and returns the result. In the component's services/provider.php, $container->extend() takes the factory that Joomla's own provider made and returns it wrapped:
$container->registerServiceProvider(new MVCFactory('\\Acme\\Component\\Shop')); // Joomla's provider, untouched
$container->extend(
MVCFactoryInterface::class,
function (MVCFactoryInterface $factory, Container $container) {
$wrapper = new ShopMVCFactoryWrapper($factory);
$wrapper->setExchangeRates($container->get(ExchangeRatesInterface::class));
return $wrapper;
}
);
In order to get that working, the core needed an MVCFactoryWrapper base class, from which you could extend your custom MVCFactory. Unfortunately the pull request was never merged. But, although the approach is a bit different, in Joomla 6.2 we at last have a solution for a custom MVCFactory where you don’t have to rewrite the code for Joomla’s standard dependencies.
Joomla 6.3? Let the container do the wiring
In all the code so far, a human writes the wiring: "if the object wears this label, call this setter with that service". Draft PR #48193 by Harald Leithner, "Introduce Autowire Factory for MVC Objects", wants to hand that job to the container.
Autowiring means: the container looks at a class, sees what it asks for, and fetches it by itself. The DI-container could already do this with buildObject() for constructor injection. But the MVCFactory never used it. One reason: MVC classes also get a runtime $config array, for example ['ignore_request' => true], and buildObject() had no way to pass such a value. That is one reason why the factories above use setters.
The PR solves this with an adaptation of the DI-container, such that scalar values, like $config, can also be put into it. Then the container is injected into the new AutowireFactory, which lets the container build each object. A class can ask for its services in two ways:
ConstructorAutowireInterface: list them as typed constructor parameters.AbstractAutowireInterface: list them in a staticgetAutowireResources()method, as a map from setter to service. In this way the setters that we had will still work. That makes it backwards compatible.
The buildObject() method of the DI-container could already solve the constructor-injected objects of a class implementing the ConstructorAutowireInterface. In the autowire branch of the DI-container this method was expanded to also solve the setter injection of a class implementing the AbstractAutowireInterface.
When merging this PR you don’t have to write a custom factory class, a custom provider, and even an aware interface anymore. The exchange-rate service only has to be registered in the container, with the recipe from the start of this article.
The PR converts com_contact as a first example. It is still in a draft stage and under discussion, but it was intended for Joomla 6.3.

Joomla 7 and beyond
Dependency injection is meant to make our lives as developers easier. Joomla 6.2 stops us from copying core code. Joomla 6.3 could stop us from writing the wiring at all.
Dependency injection was implemented in Joomla CMS version 4. It was done with setter injection to not break backwards compatibility. When instantiating with constructor injection, you cannot create an object without its required dependencies. Refactoring the core MVC classes to get rid of the $config array and other scalar values would make that possible. And you wouldn’t need to jump through hoops to get the autowiring working, because we can just use the buildObject() method that is in the DI-container from the start. If we manage to create a new set of MVC classes the coming year, then the existing MVC classes could be deprecated in Joomla 6, but have to be kept until Joomla 8 is released. So, after refactoring the MVC classes we would still need to use the old classes until at least autumn 2029. In the meantime, the proposed Autowire Factory for Joomla 6.3 could be a practical solution to make the use of dependency injection simpler; as it should be.

Comments