Question

I am quite confusing on the concept of Resource Model and Repository in Magento 2.

Are they both responsible for managing the persistent storage, like MYSQL?

Let says I would like to get specific customer model by ID from MYSQL, how do Resource Model and Repository work, to return correct result?

Please kindly correct me if I mis-understand the concept.

Thanks a lot!!!!

Was it helpful?

Solution

Resource models are the way models were handled in Magento 1 and are still available in Magento 2. Repositories are the way we are supposed to handle model storage and retrieval in Magento 2, but their use is not consistent.

Resource model way of loading would be something like:

<?php

class SomeClass {
    public function __construct(\Magento\Customer\Model\CustomerFactory $customerFactory)
    {
        $customer = $customerFactory->create();
        // load concrete customer instance
        $customer->getResourceModel()->load($customer, $someCustomerId);
    }
}

repository equivalent would be:

<?php

class SomeClass {
    public function __construct(\Magento\Customer\Model\ResourceModel\CustomerRepository $customerRepository)
    {
        /** @var \Magento\Customer\Model\Data\Customer $customer */
        $customer = $customerRepository->getById($someCustomerId);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top