[UPHPU] Fluent interfaces

Alvaro Carrasco alvaro at epliant.com
Tue May 8 16:39:22 MDT 2007


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?
>
> Richard
>
> Sources:
> http://pear.php.net/manual/en/package.webservices.services-yahoo.examples.php 
>
> http://www.mikenaberezny.com/archives/35
> http://devzone.zend.com/node/view/id/1362
>
>

I think it's pretty handy for implementing Domain Specific Languages 
used for configuration or routing (i've seen it used very effectively on 
camel http://activemq.apache.org/camel/routes.html ), but i probably 
wouldn't use it for my day-to-day programming.

Alvaro



More information about the UPHPU mailing list