Factories

Factories are classes that create other classes—much like the object manager, except this time we are encouraged to use them directly. Their purpose is to instantiate the non-injectable classes—those that we should not inject directly into __construct. The beauty of using factories is that, most of the time, we don't even have to write them, as they are automatically generated by Magento unless we need to implement some sort of specific behavior for our factory classes.

By doing a lookup for the Factory $ string across the entire <MAGENTO_DIR> directory's *.php files, we can see thousands of factory examples, spread across the majority of Magento's modules.

While a great deal of these factories actually exist, others are automatically generated when needed.

Let's take a quick look at one automatically generated factory, that of MagentoNewsletterModelSubscriberFactory, which is used in several Magento modules such as the newsletter, subscriber, and review modules:

class SubscriberFactory {
protected $_objectManager = null;
protected $_instanceName = null;

public function __construct(
MagentoFrameworkObjectManagerInterface $objectManager,
$instanceName = '\Magento\Newsletter\Model\Subscriber'
) {
$this->_objectManager = $objectManager;
$this->_instanceName = $instanceName;
}

public function create(array $data = array()) {
return $this->_objectManager->create($this->_instanceName, $data);
}
}

The autogenerated factory code is essentially just a thin wrapper on top of an object manager create method.

Factories work well with the di.xml preference mechanism, which means we can easily pass interfaces into the constructor, like so:

public function __construct(
MagentoCatalogInventoryApiStockItemRepositoryInterface $stockItemRepository,
MagentoCatalogInventoryApiStockItemCriteriaInterfaceFactory $stockItemCriteriaFactory
) {
$this->stockItemRepository = $stockItemRepository;
$this->stockItemCriteriaFactory = $stockItemCriteriaFactory;
}

// $criteria = $this->stockItemCriteriaFactory->create();
// $result = $this->stockItemRepository->getList($criteria);

The preference mechanism makes sure that concrete implementations get passed to the object instance when its constructor is invoked.

While in developer mode, Magento performs automatic compilation, meaning that changes to di.xml are automatically picked up. Sometimes, however, if we stumble upon unexpected results, running the bin/magento setup:di:compile console command or even manually clearing the generated folder (rm -rf generated/*) might help sort out the issues.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.85.76