工厂是服务类。
对象管理器(ObjectManager)
Magento\Framework\ObjectManager 负责实例化对象的Magento应用类。 Magento禁止直接使用对象管理器(ObjectManager) 在你的代码中。
Magento\Framework\ObjectManager
namespace Magento\Framework\App\Config; class BaseFactory { /** * @var \Magento\Framework\ObjectManager\Interface */ private $_ObjectManager; /** * @param \Magento\Framework\ObjectManager\Interface $ObjectManager */ public function __construct(\Magento\Framework\ObjectManager\Interface $ObjectManager) { $this->_ObjectManager = $ObjectManager; } /** * Create config model * @param string|\Magento\Framework\Simplexml\Element $sourceData * @return \Magento\Framework\App\Config\Base */ public function create($sourceData = null) { return $this->_ObjectManager->create(\Magento\Framework\App\Config\Base::class, ['sourceData' => $sourceData]); } }
您可以使用特定的模型获取工厂的单件实例 依赖注入.
下面的示例显示了一个类得到BlockFactory 通过构造函数实例:
BlockFactory
function __construct ( \Magento\Cms\Model\BlockFactory $blockFactory) { $this->blockFactory = $blockFactory; }
$block = $this->blockFactory->create();
$resultItem = $this->itemFactory->create([ 'title' => $item->getQueryText(), 'num_results' => $item->getNumResults(), ]);