Magento 2 is using factory classes for non-injectables.
For example product class: ProductFactory
For example customer class: CustomerFactory
I don’t understand what is the type of factory pattern here?
Because for each class associated with 1 factory class.
I'm thinking its something duplicate.
Why we shouldn’t create abstract factory for CustomerFactory
, ProductFactory
etc?
and also for example:
We can pass AbstractFactory
for type checking instead of ProductFactory
in ProductRepository
class constructor.
So we can avoid tight coupling between ProductRepository
and ProductFactory
Abstract Factory class:
namespace Magento\Framework\ObjectManager\Code\Generator;
/**
* Abstract Factory class
*/
abstract class AbstractFactory
{
/**
* Object Manager instance
*
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager = null;
/**
* Instance name to create
*
* @var string
*/
protected $_instanceName = null;
/**
* Create class instance with specified parameters
*
* @param array $data
* @return \Magento\Catalog\Model\Product
*/
public function create(array $data = array())
{
return $this->_objectManager->create($this->_instanceName, $data);
}
}
Abstract Factory implementation:
namespace Magento\Catalog\Model;
use Magento\Framework\ObjectManager\Code\Generator\AbstractFactory;
/**
* Factory class for @see \Magento\Catalog\Model\Product
*/
class ProductFactory extends AbstractFactory
{
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager, $instanceName = '\\Magento\\Catalog\\Model\\Product')
{
$this->_objectManager = $objectManager;
$this->_instanceName = $instanceName;
}
}
What is the relation between object manager and factory?
There is so much of chaining objects:
For example
ProductRepository
(here we can call it as client) requiresProduct
object.For this its depends on specific
ProductFactory
object.ProductFactory
object depends onObjectManager
object.ObjectManager
object depends on Factory Object (hereDeveloper Object
).
Off course they are using Interfaces for loose coupling. Still really confusing flow.
Can you someone give in-depth advantages with Magento 2 factory pattern & also how it differs from Magento 1?