Working on MVC applications has made me realize that A LOT of some strings are repeated in every single form class. For instance take Symfony Forms, it is common to see stuff like this:
<?php
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('task')
->add('dueDate', null, ['required' => false]) // repeat for n fields
->add('save', SubmitType::class)
;
}
}
Or laravel validators:
<?php
public function myMethod() {
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
'body' => 'required', // repeat for n fields
]);
}
Now, the keyword here is required
, (though there could be other strings that repeat a lot), imagine a big form with lots of required fields, you have to basically copy-paste your string every single time.
Direct approaches
Class constants: so the first thing that came to me to avoid this repetition, and possible copy-paste/grammar errors while creating a new required field, was to create a class constant.
const REQUIRED = 'required';
However the downside of this approach is that you would still have to duplicate some class constants across files. (The task form, the user form, the whatever-you-like form). And this does not seem ideal.One big class constants file: What about creating some classes where the only contents would be constants? For example:
<?php
class FormConstants {
const REQUIRED = 'required';
const LABEL = 'label';
...
}
A properties file: Simple, to the point, but kind of old school, in the sense that I don't know if this kind of approach would still be used, also kind of getting in the terrain of translations right?
Other:
What approach/other approach would you take for this problem?
Note: I use Forms and Validation as examples here for the sake of simplicity, however there could be other case scenarios where this happens.