yireo-training / magento2-di-recipes
Magento 2 的 DI 食谱
0.0.1
2017-06-14 08:52 UTC
Requires
- php: >=5.6.0
Requires (Dev)
- composer/composer: *@dev
This package is auto-updated.
Last update: 2024-09-28 03:35:13 UTC
README
此存储库包含各种用于通过 DI(类中的依赖注入)插入特定功能的食谱。
这不是一个 Magento 扩展。它仅包含代码示例。
安装
composer config repositories.yireo-training-di-examples vcs git@github.com:yireo-training/magento2-di-recipes.git composer require yireo-training/magento2-di-recipes:dev-master
基本用法
在 Magento 2 类中,您可以通过构造函数使用 DI 来注入所需的依赖项。对于这些类,如果父类已经注入了这样的依赖项,则应使用该注入依赖项。例如,如果父类提供了一个 $context
变量,请检查它是否提供了您需要的功能。
与注册表一起工作
要使用注册表,您需要注入一个 \Magento\Framework\Registry
实例。
Yireo\DiRecipes\ViewModel\Registry
与布局一起工作
在块类中,使用 $context
变量将布局的实例插入到 $this->_layout
变量中,也可以使用 $this->getLayout()
获取。或者,如果您在一个观察者或其他类似的类中,可以使用 \Magento\Framework\View\LayoutFactory
实例化自己。
Yireo\DiRecipes\Block\LayoutExample
Yireo\DiRecipes\Observer\LayoutExample
与 URL 一起工作
要注入 URL,可以注入 \Magento\Framework\UrlInterface
。但是,通过注入 \Magento\Framework\UrlFactory
获取干净的实例会更安全。可以使用 \Magento\Store\Model\StoreManagerInterface
获取当前 URL。
Yireo\DiRecipes\ViewModel\UrlExample
Yireo\DiRecipes\ViewModel\StoreManagerExample