persisting models in magento 2In the world of web development, the ability to learn from the errors and accomplishments of fellow devs is not only time saving, it is, at times, essential.

Our team of experienced developers at Human Element internally shares these handy bits of development advice throughout the week as they individually encounter blocks and are forced to do the research and get their hands dirty to figure out how to complete a task.

Here’s one super pro tip recently posted by Human Element dev, Seth Daugherty. Any time Magento stores or retrieves customer data, the application accesses a database, typically MySQL. While Magento 2 makes steps towards the best practices for persisting models, the application retains legacy code and practices from the parent Magento 1 framework.

The Pro Tip Breakdown:

Repository Pattern & Separation of Concerns

  • The Repository Pattern and Separation of Concerns (SOC) are our best friends. Magento 2 has partially implemented the Repository Pattern, which is that there are a whole new suite of repository classes that have the single responsibility of persisting/saving data to storage (file, database, etc).
  • On the other end of this relationship there are the Entities/Models that traditionally have their own `save()` methods and the ability to persist themselves to storage (breaks SOC). These types of classes should not be responsible for their own persistence.

The Problem:

  • Repository classes should be our first choice for saving entities/models (`$someRepository->save($someModel)`), but Magento doesn’t do that themselves.
  • Some required events and business logic only get triggered if you also break the patterns with Magento.
  • Ambiguity of which way to correctly save entities (you can’t just rely on the pattern when you should be able to).

The Partial Solution:

  • Assume you’ll be using repositories to save entities/models
  • Revaluate that assumption when you do it right and find out Magento doesn’t
  • Mimic Magento’s choice for now which is most likely calling `$someModel->save()`