Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

How to Validate Data
Nov 10, 2015 @ 10:18:52

In this post to thePHP.cc site Sebastian Bergmann looks at validation data, both in the sense of user input and the contents of objects you're application is currently working with.

Validating data seems to be one of the most important tasks of an application. After all, you cannot trust data from external sources. So let us have a look at how to efficiently implement data validation.

He gives an example of a user profile with requirements on the data it should contain. He focuses on the email address property as it's one of the easier options to validate (or is it). He walks through the usual progression from controller injection to setter injection of the value but wonders when the validation should happen to keep the Profile object from becoming invalid. He points out that simply having a validate method perform the checks isn't enough as it may not always be called correctly, leading to potentially invalid objects. Instead he recommends an alternative - using a validator object/tool in the setters of your object instance as the values are set. This prevents the object from getting into an unknown state and provides immediate feedback to the developer when something's wrong.

tagged: data validation object recommendation setter business rules

Link: https://thephp.cc/news/2015/11/how-to-validate-data