In Magento 2, would it be wrong to create a Factory model that allows me to get a factory for any of the models in my module? The reason I ask is that injecting model factories into my blocks/controllers where I need them and it is becoming quite difficult to manage. The proposed Factory of factories model I propose would still use DI to inject the factory classes so nothing would be hardcoded.

Here's some example code:

namespace Vendor/Module/Model;

class Factory
    protected $_factories = null;

    public function __construct(
        FirstModelFactory $firstModelFactory,
        SecondModelFactory $secondModelFactory
    ) {
        $this->_factories = array(
            'FirstModelFactory' => $firstModelFactory,
            'SecondModelFactory' => $secondModelFactory

    public function getFactory($class)
        return isset($this->_factories[$class])
            ? $this->_factories[$class]
            : false;

1 Answer 1


It's not wrong, but a) you're duplicating the responsibility of the Obj Manager and b) thus means you're actually injecting a quasi-Obj Manager, which is in itself not recommended, for various reasons (discussed here).

So, to be frank, I don't see the point in doing that.

  • It's not duplicating the object manager though because my Factory class includes all of the factories via the constructor, meaning it still uses the DI system (where as the Object Manager does not). By using this method I can include 1 object into specific files (abstract block, model and controller) and have access to the models where ever I need them while still using DI and allowing the factories to be switched out for unit testing. Commented Jun 1, 2016 at 12:46
  • It's duplicating in the sense that your Factory is not only creating objects, it stores them, too (for caching, sure). In this sense, it's an object pool. Just like the Object Manager. I didn't say they're identical, just similar enough to make your Factory class have the same disadvantages when used directly. I understand why you'd want one object instead of injecting 1000. But I still wouldn't use such a factory. I'd try refactor my existing class design, instead.
    – nevvermind
    Commented Jun 1, 2016 at 15:26

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.