On May 8, 2007, at 4:15 PM, Richard K Miller wrote:
Has everyone heard of a "fluent interface"? It's a term coined by
Martin Fowler that I just learned today. (Wondering if I've been in
the dark about this.)
Instead of returning null from your object setter methods, you
return a pointer to the object itself. This allows you to chain
together setter calls. For example, I saw this style when reading
the documentation for a new version of PEAR Services_Yahoo, which
returns search results from the Yahoo search engine:
$client = Services_Yahoo_Search::factory("web");
$results = $client->searchFor("Steve Fossett");
If you want more than 10 search results:
$results = $client->withResults(20)->searchFor("Steve Fossett");
If you want to start at the 90th result:
$results = $client->startingAt(90)->withResults(20)->searchFor
("Steve Fossett");
If you want the results returned in XML:
$results = $client->withType('XML')->startingAt(90)->withResults
(20)->searchFor("Steve Fossett");
Chaining together these options seems to make it pretty readable.
Is anybody using this style?
The jQuery Javascript framework does this quite a bit too. The most
functional example with jQuery is how they filter down through the
DOM using CSS selectors and other criteria. They also used chained
methods to pile on behaviors like animations and listeners.
I usually refer to this programming pattern as "Train Wreck" rather
than "Fluent Interface." I personally don't like the end product's
readability, and using this technique makes it a little harder to
build filter criteria dynamically. I favor passing objects or arrays
that I can combine and take apart a little easier.
-- John
_______________________________________________
UPHPU mailing list
[email protected]
http://uphpu.org/mailman/listinfo/uphpu
IRC: #uphpu on irc.freenode.net