Better Programming

Advice for programmers.

Follow publication

Member-only story

What Is the Fluent Interface Design Pattern?

Jakub Kapuscik
Better Programming
Published in
3 min readApr 12, 2020
Photo by Micah Chaffin on Unsplash.

There are concepts so simple that it is surprising they have a name. This does not mean that they are not useful. Often, the simplest concepts are the best ones for the job. A fluent interface simplifies the way we use an object’s API and promotes method chaining. It is a very useful technique for making a class's interface more expressive and easier for clients to use.

Let’s consider an example of a simple SQL query builder in PHP. We can create a select query with optional conditions:

<?php

namespace Structural\FluentInterface;

require(__DIR__ . '/../../vendor/autoload.php');

$queryBuilder = new QueryBuilder();
$queryBuilder->select(["name", "surname"]);
$queryBuilder->from("users");
$queryBuilder->where(["name = 'John'", "city = 'Warsaw'"]);
$queryBuilder->orderBy("date ASC");
$queryBuilder->limit(10);

echo $queryBuilder->getQuery();

Everything is working just fine, but it is not very handy. With a small adjustment, we can make it much more pleasant to use. Right now, each method is only responsible for adding new parts of a query, but it could also return its class instance and allow method chaining. The interface of our query builder would look like this:

<?php

namespace

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

Jakub Kapuscik
Jakub Kapuscik

Written by Jakub Kapuscik

Engineering manager at monday.com, guineafowl enthusiast

Write a response