Magento2:如何将依赖项注入 CLI 命令

Magento2: How do inject dependencies into CLI commands

我正在尝试弄清楚如何在 Magento 2 CLI 命令中正确使用或注入依赖项。来自 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.

对象管理器 (Magento\Framework\App\ObjectManager) 非常简单,尽管文档的其他部分出于某种原因不鼓励使用它。 “构造函数依赖注入”如何与 CLI 命令一起使用? Symfony\Component\Console\Command\Command的构造函数只接受一个字符串,所以这似乎没有意义。

是的,您可以在 CLI 命令的构造函数中使用依赖注入。

您可以查看一些 Magento 原生 CLI。 例如 php bin/magento store:list,您可以在 Magento\Store\Console\Command\StoreListCommand 上查看。他们将 storeManager 注入到构造函数中以正常使用它

我发现构造函数依赖缓存在 generated (M2.4.1) 目录中,必须手动删除该目录才能使 DI 正常工作。除此之外,以下 https://devdocs.magento.com/guides/v2.4/extension-dev-guide/cli-cmds/cli-howto.html 有效。