ARTICLE

Magento 2 Factories and Proxies: Generated Classes, Lazy Loading, and When to Use Each in Dependency Injection

Magento 2 Factories and Proxies: Generated Classes, Lazy Loading, and When to Use Each in Dependency Injection

In Magento 2, a factory creates a new object every time you call create(), and you use it for models that hold data. A proxy is a lazy stand-in for a service: it delays building the real object until a method is called. Both are generated classes. Factories go in your constructor, and proxies are configured in di.xml.

They solve opposite problems. A factory exists because some objects cannot be injected at all. A proxy exists because some objects are injected too eagerly. Mixing them up produces the two most familiar dependency injection bugs in custom modules: a model that carries one customer’s data into the next loop iteration, and a page that is slow because of a class it never used. This guide explains the rule behind each, how the code is generated, and where each belongs.

Injectable and newable objects

Everything starts with a distinction Adobe makes in its dependency injection guide.

  • Injectable objects are services. Adobe describes them as singleton service objects obtained through dependency injection. The object manager builds one instance per request and hands the same instance to every class that asks for it. Repositories, helpers, config readers, and loggers are injectable.
  • Newable objects hold data that depends on user input or the database. A product, an order, a quote item. Adobe states that these cannot be injected, and that trying to inject one yields an incomplete or incorrect object, or an error.

The reason is the sharing. If you inject Magento\Catalog\Model\Product into a constructor, you receive one shared, empty product. Load SKU A into it, and every other class holding that instance now has SKU A. Load SKU B in a loop, and leftover data from A can still be on the object.

So the rule is: inject services, create data objects. Factories are how you create.

Factories

What a factory is

Adobe’s factories documentation defines factories as service classes that instantiate non-injectable classes, sitting between the object manager and your business code. The naming convention is the class name plus Factory: Magento\Cms\Model\BlockFactory creates Magento\Cms\Model\Block.

You do not write that class. When a constructor references a factory that does not exist, Magento generates it.

<?php
declare(strict_types=1);

namespace Acme\Notes\Model;

use Acme\Notes\Model\NoteFactory;
use Acme\Notes\Model\ResourceModel\Note as NoteResource;

class NoteCreator
{
    public function __construct(
        private readonly NoteFactory $noteFactory,
        private readonly NoteResource $noteResource
    ) {
    }

    public function create(int $orderId, string $text): Note
    {
        $note = $this->noteFactory->create();
        $note->setData(['order_id' => $orderId, 'text' => $text]);
        $this->noteResource->save($note);
        return $note;
    }
}

Every call to create() returns a fresh instance. The factory itself is injectable and shared, which is fine because it holds no data.

Passing constructor arguments

create() accepts an array whose keys match the constructor parameter names of the class being built. Adobe’s example passes a data key to a class whose constructor has a $data parameter:

$flag = $this->flagFactory->create([
    'data' => ['flag_code' => 'acme_last_sync'],
]);

Anything you do not pass is resolved by the object manager as usual, so you only supply the arguments that vary at runtime.

Factories for interfaces

You can request a factory for an interface: Magento\Catalog\Api\Data\ProductInterfaceFactory. The generated factory asks the object manager for the interface, and the object manager returns whichever class the preference in di.xml points to. Adobe’s example is StockItemInterfaceFactory, which produces the concrete stock item model. Prefer interface factories in your own code. They keep working when another module swaps the implementation.

The generated code

A generated factory is tiny. It stores the object manager and the class name, and its create() method is one call:

public function create(array $data = [])
{
    return $this->_objectManager->create($this->_instanceName, $data);
}

This is the one place where using the object manager is sanctioned. Adobe prohibits depending on the object manager directly in your own classes, and names factories as the exception because they need it to do their job.

When to write a factory by hand

Only when creation needs logic: choosing a class from a type code, validating input before building, or assembling an object from several parts. Give it a clear name and inject the generated factories or object manager interface it needs. If your handwritten factory would contain nothing but the one line above, delete it and let Magento generate it.

Proxies

The problem they solve

Constructor injection is eager. When the object manager builds a class, it first builds every constructor dependency, and each of their dependencies, all the way down. Adobe’s proxies documentation illustrates this with a FastLoading class that depends on a SlowLoading class: the slow constructor runs every time, even on requests where the slow method is never called.

A proxy fixes that without touching either class. Adobe describes a proxy as a generated class that extends the original, implements the same interface, and creates the real instance only after one of its methods is actually called.

Configuring a proxy

Proxies are wired in di.xml, not in PHP:

<type name="Acme\Notes\Observer\AttachNote">
    <arguments>
        <argument name="exporter" xsi:type="object">Acme\Notes\Model\Exporter\Proxy</argument>
    </arguments>
</type>

The observer’s constructor still type hints Acme\Notes\Model\Exporter or its interface. It has no idea it received a lazy version. Adobe points out the benefit: because the swap is configuration, proxies can be added or removed without changing application code.

Do not type hint \Proxy in a constructor. It hard codes a performance decision into the class, breaks substitution through preferences, and Magento’s coding standard flags it.

What the generated proxy looks like

The generated class extends the original and overrides each public method to forward the call:

public function export(array $rows)
{
    return $this->_getSubject()->export($rows);
}

_getSubject() asks the object manager for the real instance the first time and keeps it. Adobe notes that each proxy has only one dependency, the object manager, which is exactly why constructing one is cheap.

Two details follow from the design. The proxy extends the class, so a final class cannot be proxied. And only public methods are forwarded, so code that reaches into public properties of the original will not behave.

Where proxies earn their place

Adobe’s guidance is short: if a class is expensive to instantiate and your class does not always use it, consider using a proxy. In practice that means four situations.

  1. Console commands. Every registered command is constructed on every bin/magento call, so heavy dependencies should be proxies.
  2. Observers and plugins on hot paths. A plugin on a method called on every page, with a dependency it needs only in a rare branch.
  3. Session and store dependent services. Classes such as the customer session or store manager do real work when built. Core itself injects Magento\Store\Model\StoreManagerInterface\Proxy into Magento\Store\Model\Resolver\Store, the example Adobe cites.
  4. Circular dependencies. If A needs B and B needs A, the object manager cannot build either. Making one side a proxy breaks the loop, because the proxy does not construct its subject up front. Treat this as a patch, and consider whether the two classes should share a third.

When a proxy is the wrong tool

  • The dependency is used on every call. You have added an indirection and saved nothing.
  • The dependency is cheap. Most small services are.
  • The real problem is a constructor that does work. Fix the constructor. A constructor should assign its arguments and nothing else.
  • You need a new instance each time. That is a factory.

Factory vs proxy vs plain injection

Plain injection Factory Proxy
What you get The shared instance A new instance per create() call A lazy wrapper around the shared instance
Use for Services you always use Models and data objects Expensive services you rarely use
Where it is declared Constructor type hint Constructor type hint on ...Factory di.xml argument with \Proxy
Generated class None Vendor\Module\Model\ThingFactory Vendor\Module\Model\Thing\Proxy
Holds state between uses Yes, shared for the request No, each object is separate Yes, same as the real service
Common mistake Injecting a model Injecting the model instead of its factory Type hinting the proxy in PHP

How and when the classes are generated

Adobe’s code generation overview lists three generated types: factories, proxies, and interceptors, the classes that make plugins work. It also explains the timing, which is the source of a classic production bug.

  • Outside production mode, a class is generated on demand when the application cannot find it. The file is written under generated/code/.
  • In production mode nothing is generated on demand. The compiler, bin/magento setup:di:compile, generates everything in advance.

So a new NoteFactory reference works on your machine the moment you save the file, and fails in production with Class Acme\Notes\Model\NoteFactory does not exist if the deployment did not compile. The fix is never to create the class by hand. It is to run the compile step. Our guide to Magento 2 deploy modes and the generated directory covers that pipeline.

Adobe also warns that generated files are not rebuilt automatically. If you add a public method to a class that already has a generated proxy, the old proxy does not forward it. In developer mode, delete the stale file under generated/code/. In production, compile again.

Interceptors are generated the same way, which is why adding a plugin also needs a compile. Our comparison of plugins, observers, and preferences explains what they do. And when you want a variation of a class with different constructor arguments and no new PHP, that is a virtual type, covered in our article on virtual types in di.xml.

Factories, repositories, and collections

Factories are not the only way to get a data object, and often not the best one.

  • To load an existing entity, call a repository: $this->productRepository->getById($id). The repository uses a factory internally and returns a ready object. See our guide to repositories and SearchCriteriaBuilder.
  • To create a new entity that you will save, use the data interface factory, fill it with setters, and pass it to the repository’s save().
  • To iterate many rows, use a collection factory. Collections hold loaded state and filters, so they are newable too. Injecting a collection directly is the same bug as injecting a model: the second caller receives the first caller’s filters.

Testing code that uses them

Factories make unit tests straightforward. Mock the factory, have create() return a mock or a real lightweight object, and assert on what your class does with it. Proxies need no special handling, because the class under test type hints the real dependency and never sees the proxy. That is one more reason to keep \Proxy out of constructor signatures.

Does Hyva change anything?

The dependency injection container is the same on Luma and Hyva. The Hyva specific habit is where you use it: templates get their logic from view models, and a view model is an injectable service. Inject factories and repositories into the view model, never call the object manager from a template, and keep expensive lookups lazy, because a view model can be constructed on pages that end up served from cache. That is the pattern our Hyva development services team follows on storefront builds.

A note on other platforms

Generated factories and proxies are specific to Magento’s object manager. Shopware uses the Symfony service container, which has its own lazy services and factory definitions. On hosted platforms such as Shopify and BigCommerce, application code runs in separate apps where you choose your own container. The underlying idea transfers everywhere: share stateless services, create stateful objects, and defer expensive work.

Where Bemeir fits

Bemeir is a Brooklyn agency that builds and maintains Magento and Adobe Commerce stores. Code review for patterns like these is part of the custom module work in our Magento development services. Read more about Bemeir or browse our technology partners.

FAQ

What is the difference between a factory and a proxy in Magento 2?

A factory creates a new object each time you call create(), and is used for models and other data holding objects. A proxy wraps one shared service and delays building it until a method is called. Use a factory when you need separate instances, and a proxy when an expensive dependency is rarely used.

Why do I get “Class …Factory does not exist” in production?

Factories are generated on demand only outside production mode. In production you must run bin/magento setup:di:compile during deployment so the class is written to generated/code/. Do not create the factory file by hand.

Should I type hint a Proxy class in my constructor?

No. Type hint the real class or interface and configure the \Proxy as the argument in di.xml. That keeps the class testable and lets the lazy loading decision be changed through configuration.

Why should I not inject a model directly?

Injected objects are shared for the whole request. An injected model is one empty instance handed to every class that asks, so data loaded by one caller leaks to the others. Inject the model’s factory and call create(), or load through a repository.

Do I need to write factory and proxy classes myself?

No. Magento generates both from the class name. Write your own factory only when creating the object requires real logic, such as picking a class based on a type code.

Let us help you get started on a project with Magento 2 Factories and Proxies: Generated Classes, Lazy Loading, and When to Use Each in Dependency Injection and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.