开发者

PHP OOP Design Patterns: Should I Create two separate classes for registration and form validation?

I have two types of registration, registration A and registration B, each will have some of the same fields and some different fields. I was going to create abstract class registration and both A and B would have their own classes that extend from registrati开发者_如何学编程on.

Should I create a separate Validation class with separate A and B validation classes that extend? or is there a better pattern to use for something like this?


I would take Registration and Validation as separate entities yes.

Edit: Also, this SO question might contain some valuable information for you.


Create a Validator abstract class with a method 'isValid()' and extend to your need.

Create a class Registration with a method validate() taking Validator object to pass through.

It'll allow to validate anything with any validator you wrote.


Yes, you probably want separate registration and validation entities. The pattern you suggested, with an abstract base and a ValidationA and ValidationB that extends it would work. If you don't really have a "default" validation, you could just make Validating an interface, and have ValidatingA and ValidatingB that implement it, and then you'd be able to use runtime polymorphism to call the proper Validate method.

One thing I've begun to realize is that you can ask and ask and discuss and muse over this kind of thing all you want, but you'll never know until you try it. Whip up a quick abstract base class and two that extend it and see if it accomplishes what you want. If not, just refactor. Sure you have to consider technical debt, etc., but just give it a shot - it's the best way to learn.


You can create its own Validator/ShowField class for every field type (e-mail, phone, login, password). You do it only once. Then you can create a Form class that will encapsulate all standard "dirty" work with the form (validating fields, showing form, showing validation messages if needed etc.)

Example of usage:

$form = new Form($action, $method); // $action and $method - html attributes of the form
$form->addField('Your e-mail', 'mail'); // field label (for the form) and field type (for the form and for validation)
$form->addField('Login', 'login');

$form->process(); // show form to the user or process it if already submited and sent

Your benefits:

  1. You create field validators once.
  2. You create Form class will all form processing once.
  3. All you do is define form fields as shown below.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜