In Magento 2, a Proxy class is a special class automatically generated by Magento’s code generation system to delay the loading (instantiation) of heavy or resource-intensive classes until they’re actually needed.
This improves performance and reduces memory usage, especially in dependency injection (DI) where certain classes may not always be required during the request lifecycle.
A Proxy class acts as a stand-in or placeholder for the real class.
The real class will only be instantiated when a method on the proxy object is called, not when the object is first injected.
Magento automatically creates proxy classes with the suffix Proxy.
Example:
Original class:
Magento\Catalog\Model\Product
Proxy class:
Magento\Catalog\Model\Product\Proxy
In your module’s di.xml, you can specify a proxy like this:
<type name="Vendor\Module\Model\SomeClass">
<arguments>
<argument name="product" xsi:type="object">Magento\Catalog\Model\Product\Proxy</argument>
</arguments>
</type>
Here, instead of injecting Product directly, the proxy Product\Proxy is injected.
When you request Magento\Catalog\Model\Product\Proxy, Magento:
Instantiates the proxy class immediately.
The actual class (Product) is instantiated only when needed (like calling a method).
When the class is heavy to instantiate (e.g., depends on DB calls).
When the class may not always be used in every request.
For performance optimization in dependency injection.
6. Example
class MyClass
{
private $product;
public function __construct(
\Magento\Catalog\Model\Product\Proxy $product // using proxy
) {
$this->product = $product;
}
public function getProductName($id)
{
return $this->product->load($id)->getName(); // actual Product instantiated here
}
}
| Feature | Proxy | Plugin (Interceptor) | Preference |
|---|---|---|---|
| Purpose | Lazy loading (performance) | Modify behavior before/after/around | Replace class |
| Auto-generated | Yes | Yes | No |
| Performance impact | Reduces load | Adds overhead | None |