SyntaxStudy
Sign Up
PHP Fluent Interfaces (Method Chaining)
PHP Intermediate 5 min read

Fluent Interfaces (Method Chaining)

Fluent Interfaces

A fluent interface is a design pattern where methods return $this, enabling method chaining for readable, expressive code.

Example
<?php
interface QueryBuilderInterface {
    public function select(string ...$cols): static;
    public function from(string $table): static;
    public function where(string $condition): static;
    public function limit(int $n): static;
    public function build(): string;
}

class QueryBuilder implements QueryBuilderInterface {
    private array $parts = [];

    public function select(string ...$cols): static {
        $this->parts["select"] = implode(", ", $cols);
        return $this;
    }
    public function from(string $table): static {
        $this->parts["from"] = $table;
        return $this;
    }
    public function where(string $condition): static {
        $this->parts["where"] = $condition;
        return $this;
    }
    public function limit(int $n): static {
        $this->parts["limit"] = $n;
        return $this;
    }
    public function build(): string {
        return "SELECT {$this->parts["select"]} FROM {$this->parts["from"]} WHERE {$this->parts["where"]} LIMIT {$this->parts["limit"]}";
    }
}

$sql = (new QueryBuilder())
    ->select("id", "name")
    ->from("users")
    ->where("active = 1")
    ->limit(10)
    ->build();
Pro Tip

Use static as return type instead of self to support method chaining in subclasses (late static binding).