Magento2 has multiple auto-generated class, which i know of i.e .factory,proxy. I came across Builder class on many occasions


Could anyone highlight the use of this?


Hope it will help you.


If you look at the data entities you may notice there are only methods to read from a data entity instance. So how do you create a data entity in PHP code? The answer is Magento is using the “builder” pattern where you have a class with setter methods to set all the properties, then you call a final create() method to return a new instance for you. If you hunt around the GitHub repo you won’t find the builder code. This is because they are automatically generated for you. For example, there will be a CustomerBuilder class created in the var/generated/Magento/Customer/Api/Data directory. This class will have all the setter methods. (Again, you get a handle to builders via the Magento 2 dependency injection framework.)

So how can you modify an instance of a data entity you got from somewhere? The answer is simple: you can’t! Actually doing so can be dangerous as some sections of code rely on entities not being changed (e.g. in shared caches). Instead, each builder has a populate($entity) method that will clone the attributes out of one entity into a new entity. You can then call the setter methods to change any attributes, then finally create() a new instance.

$newCustomer = $this->customerBuilder->create();

There is also a populateWithArray($nameValuePairsArray) for say populating an entity from a HTML form.

Alan Kent : We dropped builders because in practice they proved too restrictive / too much object copying. But yes, you use a factory now instead of a builder

Perfect answer by Alan : http://alankent.me/2014/10/31/magento-2-service-contract-patterns/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.