🐘 PHP Intermediate

What is the difference between method chaining and fluent interface?

Answer

Method chaining is the technique of calling multiple methods in sequence on an object: $result->method1()->method2()->method3(). This works when each method returns $this (the same object) or a new object of the same type. A fluent interface is a broader design pattern built on method chaining that creates a readable, DSL-like API. PHP examples: Laravel's Query Builder (DB::table("users")->where("active", 1)->orderBy("name")->get()), Guzzle's request builder, and PHPUnit's assertion API. To implement, return $this from methods that configure the object: public function where(string $col, $val): static { $this->wheres[] = [$col, $val]; return $this; }. PHP 8 allows : static as return type for covariant return type support in subclasses.