Implement Fluent Interfaces for Expressive Code

Implement Fluent Interfaces for Expressive Code

Create fluent interfaces to make your code more readable and expressive, especially for configuration or query building.

class QueryBuilder
{
    private $table;
    private $conditions = [];

    public function from($table)
    {
        $this->table = $table;
        return $this;
    }

    public function where($condition)
    {
        $this->conditions[] = $condition;
        return $this;
    }

    public function build()
    {
        $query = "SELECT * FROM {$this->table}";
        if (!empty($this->conditions)) {
            $query .= " WHERE " . implode(' AND ', $this->conditions);
        }
        return $query;
    }
}

// Usage
$query = (new QueryBuilder())
    ->from('users')
    ->where('age > 18')
    ->where('status = "active"')
    ->build();
← Back to Tips List