Skip to content

Validation of Domain Entities in Magento

Igor Miniailo edited this page Aug 18, 2017 · 14 revisions

Always valid entities

It’s a common question, “Where do I put validation?” Simple answer: put it where it’s needed.

But it’s not just a question of “where”, but of “when”, “what” and “why”. If we treat our entities as data holders, we might think to put all of our validation there, in the form of reactive validation, where the entity is allowed to be put into an “invalid” state.

Validation depends completely on the context of the operation you’re trying to perform. Life becomes much more complicated if we start having “IsValid” properties on our entities.

In domain-driven design (DDD) there is a consideration of the always valid entity (entities which are always in a valid state). There is no need to allow the entity to enter an invalid state. From the DDD perspective, validation rules can be viewed as invariants (the logical assertions that are held to always be true ).

If you let your entities become invalid, you’ve most likely lost the context of what operation was being performed on the entity in the first place. An entity may change state for a wide variety of reasons for a wide variety of operations, so certain attributes may be valid in one operation and invalid in the next.

Thinking operationally

Instead of thinking of changing state on an entity, we need to move up to a higher level of command/query separation, where we perform and execute commands on one or many entities. Instead of answering the question, “is this object valid”, try and answer the question, “Can this operation be performed?”. Because our Service Contracts (command objects) know answers to all of the “Who, what, why” questions, they are in the best position to perform contextual validation based on the operation the user is trying to execute.

Validation Types

There are two major types of validation:

  • Task-based where you don’t need to map validation errors to UI elements (happens in Magento Service Contract Commands).
  • CRUD-y where you do need to do that (happens in Magento Repositories).

Validation in Magento

Based on the above it's decided to follow the practice of having always valid entities in the system. And make the Service Contract Command Services being responsible for Domain Entities validity. If the Entity is being created in a code of business logic, a creational pattern (Factory/Builder) which is used for entity instantiation should take a responsibility of preparation and validation of entity before the creation.

MSI Documentation:

  1. Technical Vision. Catalog Inventory
  2. Installation Guide
  3. List of Inventory APIs and their legacy analogs
  4. MSI Roadmap
  5. Known Issues in Order Lifecycle
  6. MSI User Guide
  7. DevDocs Documentation
  8. User Stories
  9. User Scenarios:
  10. Technical Designs:
  11. Admin UI
  12. MFTF Extension Tests
  13. Weekly MSI Demos
  14. Tutorials

Clone this wiki locally