Should I create a class for each "input", or are only methods of a "form" class enough?

Asked

Viewed 165 times

3

Well, I’m having a logical question. I started learning PHP OO recently, so this question is more for educational purposes than anything else.

My goal is to create a class "form" that will build HTML forms. This class will have attributes like "id", "name", "method" and "action" and methods like openForm() - to start the form with such attributes, closeForm() - to close the form, and the patterns as set and get for the attributes.

My initial idea was to create methods for each input of this form on this form class, as an example newInputText(), that would create a input text-type, newButtonSubmit(), that would create a button Submit and so on (note that each of these methods would have its own HTML parameters like "id", "name", "class" and so on).

My question is: the creation of inputs and Buttons, for example, it should be done by class ""form, OR I should create a new class separate to each of them, with its own attributes and methods? What would be the most "optimized" way for such an application?

Hypothetical example of code:

$form1 = new Form("teste", "teste", "#");

$form1->openForm();

$form1->newInput("input1", "input1", "Oi");
$form1->newButtonSubmit("btnSend", "btnSend", "Enviar");

$form1->closeForm();
  • 1

    Normally frameworks use static methods because there is no need to store values, something like Form::input(array('name' => 'nome', 'id' => 'nome', 'class' => 'css-input'))

  • 2

    It is usually interesting to generalize first to then specify. For example, have the method Form::input that generates the tag input, being able to handle all its properties, as a generic method; and, if desired, create others such as Form::inputText and Form::inputPassword using the generic method, defining the necessary properties.

1 answer

0

Try to work with the use of Namespaces and Single Liability Principle (where a class should have only ONE responsibility). 'Cause then you’ll get a bigger reuse of code and maintenance gets less painful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.