0

If I want to save data in controller's action, what should I inject?

  1. Model Class or Repository Class
  2. Model Factory or Repository Factory

.

use Krish\Database\Api\Data\TestInterface;
use Krish\Database\Model\TestModel;
use Krish\Database\Model\TestRepository;
public function __construct(
    Context $context,
    TestInterface $testInterface,
    TestModel $model,
    TestRepository $testRepository
)
{
    parent::__construct($context);
    $this->testInterface = $testInterface;
    $this->model = $model;
    $this->testRepository = $testRepository;
}
public function execute()
{
    $this->testInterface->setName('Through Repository');
    $this->testRepository->saveTest($this->testInterface);

    $this->model->setData('name','Through Model');
    $this->model->save();
    exit;
}

In above code, Data is saving from both Model and Repository. This code also works fine with below constructor:

use Krish\Database\Model\TestModelFactory;
use Krish\Database\Model\TestRepositoryFactory
use Krish\Database\Api\Data\TestInterface;
public function __construct(
    Context $context,
    TestInterface $testInterface,
    TestModelFactory $model,
    TestRepositoryFactory $testRepository
)
{
    parent::__construct($context);
    $this->testInterface = $testInterface;
    $this->model = $model->create();
    $this->testRepository = $testRepository->create();
}

1 Answer 1

0

As a general rule you should inject either

  • Model Factory
  • Interface Factory
  • Repository Interface

Although the second two are the preferred option to avoid deprecated functionality

Update

Why factory? And not model class?

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.

https://devdocs.magento.com/guides/v2.3/extension-dev-guide/factories.html

Do not use model class because that's not the correct way to use the framework.

Model factory or Repository and Why

At this stage personal preference. Factories are similar to Magento 1 style of things. However the code is slowly being deprecated. It is prefered to use repositories. The general rule of thumb is that repository code will not change whereas logic underneath could change. Which means that if you write something once it is more likely it will work on future versions of magento. However does mean that you are writing more verbose code.

1
  • please describe "why". First Question is what to use Factory Or Class and why? Second Question is What to use Model or Repository and Why?
    – 26vivek
    Commented Nov 12, 2019 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.