What is Different between Repository and Factory

Hello,

What is Different between Repository and Factory 


1.  Repository :-  A repository object is responsible for reading and writing your object information to an object store. 

>> Repository is the Model that is supposed to be used to expose the data for a given entity. In practice, they may optimise how the data is loaded. For instance, product repository uses a caching mechanism.


2. Factory :- Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code.

>> Factory is used to create an instance of a Model that loads an entity (Magento auto-generates Factory class in generated folder)


Similarity  of Repository and Factory  

>> In short,they both lead to read/gather data for an entity.


Different of Repository and Factory


>> If the entity is meant to be exposed with an API, the repository will be the model used whereas factory only loads data (and returns an object). Factory has more granularity than repository; meaning it is easier to customise the collection factory query than customising a repository getList method (playing with extension attributes is more abstract than playing with sql)


How to Use in Code 

Retrieve Data

Using A Factory Approach

$object = $this->myFactory->create();
$object->load($myId);

Using A Repository Approach

$repo   = $this->myRepository();
$object = $repo->getById($myId);

Save Data

Using A Factory Approach

$object = $this->myFactory->create();
$object->load($myId);
$object->setData('something', 'somethingDifferent')->save();

Using A Repository Approach
$repo   = $this->myRepository();
$object = $repo->getById($myId);
$object->setData('something', 'somethingDifferent');
$repo->save($object);
Thanks ...

Comments