Sitemap

Stop copying Symfony docs – learn anemic vs rich models first

3 min read3 days ago

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.

Press enter or click to view image in full size

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web
Already have an account? Sign in
Bohdan Pastukh
Bohdan Pastukh

Written by Bohdan Pastukh

Engineering Manager | PHP & Symfony Expert | Mentor & Career Coach for Developers https://www.linkedin.com/in/bohdan-pastukh/

No responses yet

Write a response