skip to Main Content

I’m trying to figure out how to use or inject dependencies properly in Magento 2 CLI commands. From https://devdocs.magento.com/guides/v2.4/extension-dev-guide/cli-cmds/cli-howto.html:

Your command can use the Object Manager and Magento dependency injection features; for example, it can use constructor dependency injection.

Object Manager (MagentoFrameworkAppObjectManager) is simple enough, even though other parts of the doc discourage use of it for some reason. How does "constructor dependency injection" work with CLI commands? SymfonyComponentConsoleCommandCommand‘s constructor just takes in a string, so that doesn’t seem to make sense.

2

Answers


  1. Chosen as BEST ANSWER

    I found out the constructor dependencies were cached in the generated (M2.4.1) directory, which had to be manually removed for the DI to work properly. Other than that, following https://devdocs.magento.com/guides/v2.4/extension-dev-guide/cli-cmds/cli-howto.html works.


  2. Yes, you can use dependency injection into the constructor of CLI commands.

    You can check on some Magento native CLIs.
    Example php bin/magento store:list, you can check on MagentoStoreConsoleCommandStoreListCommand. They injected storeManager into the constructor to use it like normally

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search