Validation is important in any application. You need to be sure that any data entered by a user is valid before its persisted or inserted in a database. Your data can become very messy if you don’t validate its correctness. Your business logic can do all weird kind of ‘buggy’ things, because its in an inconsistent state.
As with anything in your life. You want it to be clean and in a consistent and correct state as much as possible.
One place of validation?
The easiest and most common way is to use the Symfony Validator and its annotations to assert your entities validation in the Entity object. Then we take the data from the user, place it nicely in the Entity and then validate of the data in that Entity is correct or not. If not we throw a big fat error. We don’t save the Entity (phew). And we tell the user to try again. Off course we show some nice clean and easy to understand message.
So whats wrong with this?
There is nothing wrong if your Entity is just a data object. This means, it has no business logic and only consists out of getters and setters. In that case we don’t care if the Entity exist in an invalid state.
For short living and small applications, this might not be a problem. But is there a better way?
Exceptions, Exceptions, and more Exceptions?
You should consider your Entity as a Domain Object. When I talk about an Entity or Domain Object. I mean the same thing. But its actually not the same thing. And Entity only has an id. Its an object that can be identified. That’s exactly, the only requirement for a class to be called an Entity.
But an Entity becomes a Domain Object when it has business logic. When it actually means something in your domain. The business. Anything happening in here defines how the business works.
This means, your Domain should NEVER consist of invalid data. You NEVER insert data that is not valid for your domain or business. All data needs to be validated, before its actually saved in your Domain Object (or Entity).
Users and clients can never directly interact with this Domain Object. Only the application is allowed interaction. But we can’t fully trust this application. There could be multiple applications using the same Domain layer. And any of those applications has its own validation.
The validation of your domain is handled by exceptions. Anything that comes inside the domain layer needs to be valid. We don’t validate input, we validate data. If for any reason the data is incorrect. We throw clear exceptions. These exceptions are for the applications developer. Not for the user or client interacting with the interface. They will only see domain exceptions when the application developer failed in its validation.
So now that we know that we should use exceptions to validate our Entities. But how do actually implement validation for data that is entered by users or comes from external service/clients?
Well for this we can use the Symfony Validator component.