I'm making some sort of personal framework, for educational and practical purposes, and encountered a design problem i'd like to share.
I have a Component
namespace, that contains various classes for, um, components (i. e. bits of reusable ViewModels). One of them is Component\Form
, a generator class for building form templates from models. After some time i realized a need for some Validation
service classes, that will perform non-model specific validations, like checking captcha.
The problem is, my default form validation accumulates error messages and displays them in one place. So, to accomplish this, my Validator
classes need to have access to the Form
, and Form
class adds Validator
classes via setter injection.
So, this creates circular dependency. From one side, there's an (although optional) dependency of Form
on Validator
classes, and from other side, i have to inject a Form
class into every Validator
i add. I wonder, if this approach is fine from the point of OOP design, and if not, what problems could possibly arise from that, and how could i possibly resolve it.
I'm sorry i don't provide any relevant code, i think it would take too much space to be readable, but if necessary, i'll gladly post anything to clarify specific moments of the problem.
I think the validator should not have a dependency on the form, because it should not display an error. The form can ask the validator to check some raw input against some rule. If the validation fails, the validator might return an error code or message, based on which the form can display an error. Displaying that error is not the job of the validator.
i would say that you miss some kind of mvc. i would keep that the validator depends on form as it have to access all data and passing raw values will be tedious and complex (comparing two passwords, captcha, checking if one field is longer that 5 only if another is shorter than 3). but i would not make that a form depends on a validator. because form doesn't know if it requires a validation. sometimes you need to trigger validators A and B and sometimes B and C. and form doesn't have the knowledge to make that decision. that's the controller's job. i would add some kind of ValidationGroup / ValidatorHandler etc. which references a form and (a group of) validators. then a controller would trigger the correct group of validators