In what case we need to run this command
magento setup:di:compile ?
During deployment (i.e. when changes were made to a system in production mode)
Note that in production mode (versions 2.0.5 and earlier) you must use the "multi-tenant" compilation. Fixed in 2.0.6 and later.
You can also use compilation in development mode, which should speed up the site, but on the other hand it slows down development, because you will need to run
bin/magento setup:di:compileeverytime you added new classes with dependencies (constructor parameters) or changed dependencies of existing classes.
This is optional, and it's probably not a good idea. If you already ran the compilation in your development environment, delete the files in
var/dito disable it.
As per my comment on another answer:
You can avoid running the
setup:di:compile command after every time you add a depency by just deleting the
var/generation folders before reloading the page.
From my own tests, Magento will recreate the
var/generation folder, but not the
var/di folder until
setup:di:compile is ran again. This means you should only have the
var/generation folder to delete.
Funnily enough, this also works with
setup:static-content:deploy. This is because Magento seems to create symlinks to the files needed if the static content is built by page reload, rather than CLI.
People in our office were having problems running the above commands whilst using Docker for Mac. The file processing was just too slow. By using the steps above, development should be much quicker.
It's probably best to note that this will not work when in production or default mode. This is only for development. As mentioned by Fabian Schmengler, initial page reload will be slower than normal, but shouldn't be as slow as running
setup:static-content:deploy or `setup:di:compile.
For reference, I am running version 2.1.5.
Taken from Alan Storm's blog.
Dependency Injection Compilation
To start, we should explain the problem these commands are trying to solve. When you ship a Magento 2 system to production, you need to run the following command
php bin/magento setup:di:compile
This commands scans through the code in your system and pre-generates a number of things (mostly related to the object manager system and dependency injection) that Magento dynamically loads when you’re running in developer mode. This is both a performance and security thing, and discussing it in full is beyond the scope of this article.