Member-only story
Stop copying Symfony docs – learn anemic vs rich models first
Link for non-Medium members.
Symfony documentation teaches you an Anemic Model design. Imagine a simple User entity:
class User
{
private int $id;
private string $username;
}Now the manager asks to add contact fields:
class User
{
private int $id;
private string $username;
private string $contactType;
private string $contact;
public function setContactType(string $contactType): void
{
$this->contactType = $contactType;
}
public function setContact(string $contact): void
{
$this->contact = $contact;
}
}Then you create a service to change contact data:
class ContactDataService
{
public function changeContactData(string $contactType, string $contact): void
{
if ($contactType === 'email' && !$this->isValidEmail($contact)) {
throw new InvalidEmailException($contact);
}
$user = // retrieve user;
$user->setContact($contact);
$user->setContactType($contactType);
}
private function isValidEmail(string $email): bool
{
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
}Looks familiar? This is the kind of design often shown in Symfony documentation and tutorials.