php – Should I create a class for each "input", or is just methods of a "form" class enough?

Question:

Well then, I have a logical doubt. I started learning PHP OO recently, so this question is more for educational purposes than anything else.

My goal is to create a "form" class 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 defaults like set and get for the attributes.

My initial idea was to create methods for each input of this form in this same class , such as newInputText() , which would create a text type input , newButtonSubmit() , which would create a submit button and so on (note that each of these methods would have their own HTML parameters like "id", "name", "class" and so on).

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

Hypothetical code example:

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

$form1->openForm();

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

$form1->closeForm();

Answer:

Try to work with the use of Namespaces and Single Responsibility Principle (where a class should have only ONE responsibility). So you will have a greater reuse of code and maintenance is less painful.

Scroll to Top