1

As Magento prohibits depending on and directly using the ObjectManager, whether all object can use factory object to instantiate?

1 Answer 1

1

Short answer: YES.
Long answer.
All the objects that are not instantiated directly using new can have a factory.
By that I mean if you have a class Some\ClassName and you try to instantiate the factory class for this class that does not exist new Some\ClassNameFactory most probably it will not work.

But any factory that does not exist but it used as a dependency for an other class gets automatically generated as long as the class name ends with the keyword Factory.

Example:
You have this constructor

public function construct(
    SomeClassFactory $someClassFactory,
    OtherClassFactory $otherClassFactory, 
    EvenOneMoreFactory $evenOneMoreFactory
) {
    ....
}

if the classes SomeClass, OtherClass and EventOneMore exist, the factories will be autogenerated.

If you manually created the classes SomeClassFactory, OtherClassFactory or EventOneMoreFactory for some reason, they will not be autogenerated anymore. Your factory classes will be used.

2
  • thx, Marius. is there any object can not use Factory Object to instantiate in magento 2?
    – Liang
    Commented Apr 11, 2017 at 15:44
  • what is “ non-injectable ”classes, the official docs says Factories are service classes that instantiate non-injectable classes.
    – Liang
    Commented Apr 11, 2017 at 15:56

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.