D
D
Danbka2017-11-22 10:28:57
PHP
Danbka, 2017-11-22 10:28:57

How to validate a large number of class properties?

Hello.
Suppose there is a certain web service that accepts user data as input: full name, gender, profession, city, etc., there are about 20 of them in total. All are required.
I need to work with this service.
To do this, I have a User class, which has a bunch of properties:

Class User {
  private $lastName;
  private $firstName;
  private $city;
  ....
}

When you create an object of class User, you must set the values ​​of these properties.
Do I understand correctly that I will have 20 methods like setLastName(), setFirstName(), setCity(), etc.? Is this normal practice? Or is there a more "beautiful" way?
Also, where should the value validation take place? In the same methods?
I am also confused by the "ugly" code of the form:
$user = new User();
$user->setLastName('Ivanov');
$user->setFirstName('Dmitriy');
$user->setCity('Moscow');
....

those. about 20 lines with setting values.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Matvey Pravosudov, 2017-11-22
@oxyberg

Use the __set and __get magic methods to avoid creating a bunch of getters and setters.

N
Nikolai Konyukhov, 2017-11-22
@heahoh

For example, yii uses this approach for validation

D
dmitriy, 2017-11-22
@dmitriylanets

$user = User::fromState([
"LastName"=>"Ivanov",
"FirstName"=>"Dmitriy"
]);

the method itself should also work through set-ry

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question