Reputation: 11
I want to create an HTML form to store information about enterprises in a database. Is it a good idea to use OOP? I wanted to create an "Enterprise" class, and every set(...) method has check methods, to validate the form.
An enterprise object would be filled with the information from the form. An exception is thrown if the data is invalid, which should result in an error message in the HTML form.
If everything is correct, the attributes / information would be written into the database.
Upvotes: 0
Views: 2438
Reputation: 87
I don't know if "form" OOP pattern exists but in our project using onPHP framework we have such class. I really love to use it for validating and preprocessing any incoming data "from the world". If you don't use any framework maybe it's a good idea to start using any recognized one because most of them have model/form validation functionality. Just an example for giving the idea:
/* @var $request HttpRequest */
$form = AccountFormFactory::getRegistrationForm()
->import($request->getPost())
->checkRules();
if ($form->getErrors()) {
// didn't pass validation, do something
...
}
And somewhere in AccountFormFactory::getRegistrationForm()
$form
->add(Primitive::string('email')->setPattern('~regex pattern~')->required())
->add(Primitive::string('password')->required())
->addMissingLabel('email', TranslationMarkers::REQUIRED_VALUE)
->addMissingLabel('password', TranslationMarkers::REQUIRED_VALUE)
->addWrongLabel('email', TranslationMarkers::INVALID_EMAIL)
->addWrongLabel('password', TranslationMarkers::INVALID_PASSWORD)
->addRule(
'uniqueEmail',
function (Form $form) {
$email = $form->exportValue('email');
if (User::dao()->findByEmail($newEmail)) {
$form
->markWrong('email')
->addWrongLabel('email', TranslationMarkers::DUPLICATE_EMAIL);
}
}
);
Upvotes: 0
Reputation: 2784
Using OOP is typically a good idea (unless your project is very small). Here is a link to another question where somebody already wrote a class for doing what I think you are attempting. Nearly all frameworks provide some sort of validation class. Looking through the code for any of them will be a good experience.
Upvotes: 1
Reputation: 101
So, in the end, you will need to have some class which matches the Database table that you will insert this data in to.
If you envision that your form will need to support a number of mainly similar yet slightly different 'Enterprises', you can create a super 'Enterprise' class and subclass it for each different enterprise you wish to support.
Otherwise, if you think that your definition of an 'Enterprise' will remain relatively static, the added complexity of creating an object oriented hierarchy would be time you could better spend working on the rest of the application!
Upvotes: 0