Fluent Setters with Doctrine Entities

Getters and setters are a necessity with Doctrine entities. Instead of returning void with a setter, you can reduce the excess code in places like controllers where setters are frequently used by making them fluent.

Before going into detail, a quick explanation of what a fluent method is: This refers to a set of methods that self-referentially return the current object to allow for method chaining.

An example of using setters without fluent methods:

$employee = new Employee();
$employee->setName('Joe');
$employee->setTitle('CEO');

Expressing the same code with fluent methods in place:

$employee = new Employee();
$employee
    ->setName('Joe')
    ->setTitle('CEO');

Both approaches are perfectly valid and the result will be the same; however, the flow of code reads much more cleanly using the fluent approach.

To implement this in your entities, just return $this at the end of each setter. For example, if your setters look like the following (using our Employee entity):

public function setName(string $name): void
{
    $this->name = $name;
}

Just change them to the following:

public function setName(string $name): Employee
{
    $this->name = $name;
    return $this;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.