Code Generation in Magento 2

When and Why Does Code Get Created in /var/generation?

Overview

Code generation can be triggered in two ways:

1. On the fly – when the system tries to autoload a class, if it doesn’t find it, it generates it. (slower)

delete the MAGENTO_ROOT/var/generation directory

2. Command-line – process goes through the system, inspects the code, and generates the necessary classes it might need. (speedier)

run the magento setup:di:compile command from terminal on web server

Code Generation did not exist in Magento 1. In Magento 2, code generation is deployed to support a number of core concepts.

The system generates several class types – the 3 most important are Factories, Proxies, and Plugins.

Factories

Factories are used to instantiate objects that cannot be injected automatically, objects that it doesn’t make sense to create with a generic mechanism, such as those which contain data from the database.

  1. Developer declares a dependency on factory in constructor ($productFactory)
  2. Object manager injects this dependency
  3. Developer can access create() method (the only method in factory object) to create as many Product instances as he wants.

The purpose of factories is to delegate object instantiation to object managers.

Proxies

Magento 2 uses the object manager to create all the dependencies and allows only one type of dependency injection: constructor injection. Thus, you cannot instantiate an object without passing all the dependencies as they are required. Proxies allow you to pass in optional dependencies.

Developer never touches PHP files to use proxy, only inside the di.xml

Whenever any proxy method is called for the first time, the original instance gets created with all its dependencies. The purpose of a proxy is to delay creation of an instance (and its dependencies) until the very first usage.

Plugins (Interceptors)

Plugins are the primary customization mechanisms for Magento 2 which replace class rewrites. Plugins allow you to hook in and do something before, after or around any public method of the application.

  1. Developer writes a plugin class depending on the requirements
  2. Developer registers a plugin in di.xml

The system generates the interceptor class. The generator tool will generate only the methods that you rewrite.

Leave a Reply

Your email address will not be published. Required fields are marked *