0

I want to initialize some data on factory->create() without passing in the create(["mydata" => 1]).

What's the way to create MyFactoryClass with custom create() for MyClass in my module?

I find not dev doc for the same or any article.

1 Answer 1

2

Let's say that your class for which you want the factory is this Vendor\Module\Model\MyClass.
now you can create the class Vendor\Module\Model\MyClassFactory in the same folder as your initial class.

namespace Vendor\Module\Model;

class MyClassFactory implements MyInterface
{
 .....
     public function create() 
     {
     ......
     }
}

class MyInterfaceFactory extends MyClassFactory
{
    // this class is added so that there no Type Error
    // while using MyInterfaceFactory/MyClassFactory
}

Creating this means that Magento will not autogenerate the factory class for your class anymore. It will use your factory instead.

6
  • What are the benefits of factory class ? Commented Aug 31, 2020 at 12:33
  • @HamendraSunthwal. You have one single point of instantiating the same kind objects, you can mock it easily in unit tests
    – Marius
    Commented Aug 31, 2020 at 13:19
  • @Marius Thanks for the confirmation! MyClass is implemented by MyInterface so MyInterfaceFactory needs to be mapped in di.xml to my custom MyClassFactory ? Commented Aug 31, 2020 at 13:26
  • Also getting this error for no reason: Magento/Framework/Exception/RuntimeException with message 'Type Error occurred when creating object: Commented Aug 31, 2020 at 13:32
  • 1
    clear the contents of generated/code and generated/metadata
    – Marius
    Commented Aug 31, 2020 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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