Why generate code?

In brief, you can generate code to create non-existent classes. As an example, look at the \Magento\Customer\Model\Resource\AddressRepository constructor. A snippet follows:

{% highlight php %} {% endhighlight %}

The first constructor parameter has a type of \Magento\Customer\Model\AddressFactory. However, this class does not exist in \Magento\Customer\Model in the Magento 2 GitHub. The Magento application generates this class as because its name uses a recognized convention (in this case, because the name ends with Factory).

Unlike some other languages or libraries, you can look at the generated code on the file system to see what really happens and still debug through the code.

When is code generated?

Provided the Magento application is not set for production mode, code is generated when the Magento application cannot find a class when executing code.

You can also use the compiler discussed in this topic to generate code at any time.

Proxies and factories

Why should you regenerate code?

Suppose a Customer or Proxy class for a Customer class is generated. The Customer class has new methods added to it. Because a Customer or Proxy exists on the file system, it will not be re-generated. However, the Customer or Proxy implementation is incomplete now because it does not have the new methods. In this case, you must regenerate the Customer or Proxy class.

Rarely, if the code generator implementation itself is changed, you must regenerate all the classes.

Advantages of generating code

Generating code assures you of the following: