What Triggers the Generation of a Factory in Magento 2

Some interesting code location for how this all works together: https://github.com/magento/magento2/blob/develop/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest.php#L40

With the different types coming mostly from here https://github.com/magento/magento2/tree/develop/lib/internal/Magento/Framework/ObjectManager/Code/Generator but also from here https://github.com/magento/magento2/tree/develop/lib/internal/Magento/Framework/Interception/Code/Generator for the Interception code.

It is all triggered by the autoloader here https://github.com/magento/magento2/blob/develop/lib/internal/Magento/Framework/Code/Generator/Autoloader.php#L32

public function load($className)
{
    if (!class_exists($className)) {
        return Generator::GENERATION_ERROR != $this->_generator->generateClass($className);
    }
    return true;
}

I am digging in this same pea soup right now. My understanding so far is that all of the stuff that gets auto generated at /var/generation is done from the preferences and interfaces declared in app/etc/di.xml.

Interfaces and preferences of yours are going to be declared in the di.xml file in your /app/code/Vendor/<module>/etc/di.xml.

It knows to generate the object(s) for you because you have declared an interface in your __constructor AND have declared a preference for that interface either globally or locally in the appropriate di.xml file.

I offer three grains of salt with my comments.


I haven't found in the code, the conditions for which the factories are generated, but from my understanding a factory class is generated when it is requested and not found.
There are some reserved keywords Factory, Proxy, Interceptor, if used, will trigger code generation when the specific classes are not found.
I will post back as soon as I find the code that triggers the factory generation.
So, if you request the class Some\Namespace\HereFactory and the class does not exist, because it ends with the keyword Factory it will be generated in the var/generation/Some/Namespace/HereFactory.php