marnaels marnaels - 1 year ago 87
PHP Question

Combine builder pattern with some kind of validation

I've design a builder pattern with some properties that I want to validate. If the validation of a property is incorrect change the content of the property before builder pattern build the object.

Is there any other pattern to combine with builder pattern to achieve this? If no
What is the best practice to do this.

Any help would be appreciated

Answer Source

If the validation logic is related to the builder logic, the place to implement is the builder class itself. But if it is related to the object you are building in the builder, move it to the constructor of the class to be built. If you think the validation logic is a subject to change, or you may have various implementation of the validation for the same builder class, create a validator interface and make an association to it from the builder class, and try to instantiate the proper validator implementation by using a Factory or DI pattern.