2

I was looking to a code example about creating custom attributes for products. I saw a class/interface in the code (Magento\Eav\Setup\EavSetupFactory). But I could not find where it is defined.

You can see that a lot of plugins have already been using this class/interface, but I could find where it is actually defined.

Where is this class defined?

7

Magento will generate any class with 'Factory' on the end itself either on the fly in developer mode or as part of the setup:di:compile process. The factory class will have a method called create that will instantiate a new instance of the class on it.

A normal example in a setup class would be as below.

class Setup implements InstallDatInterface {
    protected $eavSetupFactory;

    public function __construct(\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory) 
    {
         $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(\Magento\Framework\Setup\InstallDataInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context) 
    {
        /**
        * @var \Magento\Eav\Setup\EavSetup $eavSetupModel
        */
        $eavSetupModel = $this->eavSetupFactory->create(['setup' => $setup]);
     }
}

This is typically used so that you can load a model using dependency injection. Rather than request Magento\Eav\Setup\EavSetup, you request Magento\Eav\Setup\EavSetupFactory and then call the create method to get you the Magento\Eav\Setup\EavSetup object.

  • that's why I didn't find anything when searching the class, been stuck here for a while. Thanks man – Gujarat Santana Jul 31 '17 at 7:18
  • What is the reason that it works this way? – robsch 2 days ago
  • @robsch When you inject a class into your code via dependency injection, it is a 'shared' object (rather than a newly instantiated object each time - see alanstorm.com/magento-2-shared-instances-and-dependency for more detail). By injecting a factory object instead, you can create your own instance of the object you need. – Paul 2 days ago
  • Thanks, @Paul. My question was actually about why the Factory classes get generated and are not part in the modules. Feels strange to reference a class that might not be available. I don't see what is special about the Factory class, so that it cannot be part of a magento module. – robsch yesterday

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.