Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 42 ยท Dependency Injection

Factories, Proxies and Generated Code

Understand Magento 2 auto-generated Factory, Proxy and Interceptor classes, the generated directory and compile mode, with runnable PHP stand-ins for each idea.

Sometimes you write use Magento\Catalog\Model\ProductFactory; and inject it, yet no file named ProductFactory.php exists in the Magento source. That is not a mistake. Magento generates certain classes automatically, based on a naming convention, and the Object Manager knows how to build them. There are three kinds you will meet constantly: Factories (suffix Factory), Proxies (suffix \Proxy) and Interceptors (suffix \Interceptor, created for classes that have plugins).

This lesson explains what each generated class is for, where the code ends up, and how compile mode relates to all of this. Real Magento code is read-only; the runnable examples are stand-ins in plain PHP. One of them even generates a class at runtime, the same trick Magento uses, so you can see what such generated code looks like.

Factories: creating many objects

The Object Manager's get() returns shared instances, which is right for services: a logger, a repository, a config reader. But some objects are data: one product, one order item, one customer address. You need a new instance each time, often with values. Injecting the Object Manager to call create() would be the discouraged pattern from the first lesson of this section. So Magento gives each such class a factory: a tiny injectable class with one method, create().

The generated factory for a class is, in spirit, this (simplified):

PHP
<?php
namespace Magento\Catalog\Model;

class ProductFactory
{
    public function __construct(
        private \Magento\Framework\ObjectManagerInterface $objectManager,
        private string $instanceName = \Magento\Catalog\Model\Product::class
    ) {
    }

    public function create(array $data = []): \Magento\Catalog\Model\Product
    {
        return $this->objectManager->create($this->instanceName, $data);
    }
}

You use it by injecting ProductFactory and calling create():

PHP
public function __construct(
    private readonly \Magento\Catalog\Model\ProductFactory $productFactory
) {
}

public function newProduct(): \Magento\Catalog\Model\Product
{
    return $this->productFactory->create(['data' => ['sku' => 'demo-1']]);
}

The array passed to create() provides constructor arguments by name, merged with whatever di.xml configures. Magento also creates factories for interfaces (such as ProductInterfaceFactory), in which case the preference decides the concrete class. Rules of thumb:

  • Inject a factory when you need a new object per use, or when the class cannot be built without runtime data.
  • Inject the class or interface itself when you need the shared service.
  • Do not hand-write a factory unless you need custom behavior. If a class named SomethingFactory already exists, Magento uses it instead of generating one.
flowchart LR
    A["Your class asks for ProductFactory"] --> B{"Does ProductFactory.php exist?"}
    B -->|"yes"| C["Use that file"]
    B -->|"no"| D["Generate it into generated/code"]
    C --> E["create() returns a new Product each call"]
    D --> E

A missing Factory class is not an error: Magento generates it from the naming convention.

Proxies: lazy loading

Constructor injection builds every dependency up front, even ones used only in rare code paths. If a dependency is expensive to construct (it opens a connection, loads a big config, or pulls in many other objects), you pay for it on every request that builds your class.

A proxy is a stand-in subclass that is cheap to create and builds the real object only when you first call one of its methods. You request it in di.xml by adding \Proxy to the class name:

XML
<type name="Acme\Greeting\Console\Command\ExportCommand">
    <arguments>
        <argument name="exporter" xsi:type="object">Acme\Greeting\Model\Exporter\Proxy</argument>
    </arguments>
</type>

The class Acme\Greeting\Model\Exporter\Proxy is generated. Your constructor still type-hints Exporter, which the proxy extends, so your code does not change. A classic use is a console command: Magento instantiates all commands to build the command list, so each command should be light and use proxies for heavy dependencies. Proxies are also used to break circular dependencies between two classes. Do not proxy everything: each call goes through an extra layer, and a shared service that is always used gains nothing.

Interceptors: the plugin carrier

When a class has plugins configured (the topic of Plugins (Interceptors)), Magento generates Class\Interceptor, a subclass that overrides each public method and runs the before, around and after plugin methods around the original. The Object Manager builds the Interceptor instead of your class, and everything that asked for the original type gets the interceptor, which is still an instance of it. You never write interceptors yourself.

The generated directory and compile mode

Generated classes are written to generated/code/ (older 2.x versions used var/generation; check your version). Other precomputed artifacts, such as constructor definitions and plugin lists, go to generated/metadata/.

  • Developer and default mode: classes are generated on demand the first time they are needed, so a new constructor argument or a new plugin works right away. If the generated file gets stale or corrupt, delete the contents of generated/ and let Magento recreate it.
  • Production mode: nothing is generated on the fly. You run bin/magento setup:di:compile before switching or deploying; it scans all enabled modules, generates every factory, proxy and interceptor, and builds the metadata. If something is missing at runtime the page fails, which is why compile runs in the deployment pipeline (see Deployment and Upgrades).

When you add a plugin, a proxy or a new Factory dependency to a store in production mode, recompile and redeploy; editing di.xml alone is not enough.

A stand-in factory

The stand-in factory below holds a "class name" and builds a new object with arguments from the caller, mimicking the generated create(). The container hands out a shared service and new data objects, side by side.

PHP Factory versus shared service

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.

A stand-in proxy and generated code

A lazy proxy delays building the real object. The second example also shows code generation: it builds the source of a proxy class from reflection, prints it, and evaluates it with eval(). Magento writes the same kind of source into files in generated/code instead of evaluating it (and the real generator is far more complete). Use of eval in your own code is a bad idea; here it just keeps the example in one file.

PHP Generating a lazy proxy class

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.

Notice that the proxy extends the real class, so any constructor that type-hints HeavyExporter accepts it. The subject is created at the first method call only.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You inject Magento\Catalog\Model\ProductFactory but cannot find that file in vendor. What is going on?

    Magento generates a missing Factory class into generated/code (on demand in developer mode, during setup:di:compile for production).
  2. 2. When should you inject a factory instead of the class itself?

    A factory's create() builds a new instance every call, which is right for data objects such as products or addresses.
  3. 3. What does a Proxy do?

    A proxy extends the real class but constructs it lazily, which helps with heavy or rarely used dependencies and circular dependencies.
  4. 4. In production mode a new plugin is added in di.xml but its Interceptor class does not exist. What should you do?

    Production mode does not generate classes at request time, so the compile step must produce the new interceptor.

Summary

  • Magento generates Factory, Proxy and Interceptor classes by naming convention; you rarely write them.
  • Use a factory when you need new objects per use; inject services directly when sharing is right.
  • A \Proxy argument makes a dependency lazy, which helps with heavy constructors and circular references.
  • Interceptors carry plugins; the Object Manager builds them transparently.
  • Generated code lives in generated/code (on demand in developer mode); production needs setup:di:compile.
  • The stand-ins show the ideas (a factory, a lazy proxy, source generation), not Magento's real generator.

Next: Plugins (Interceptors)