A sensible place for a fluent interface - Blog - Open Source - schlitt.info

schlitt.info - php, photography and private stuff

A sensible place for a fluent interface

First of all: Happy new year everybody!!

The new buzz term "fluent interface" has been mentioned a lot in the PHP world recently, so I will not again explain, what a "fluent interface" is. Andi already mentioned, that this way of desining an API is quite good and can give you a really handy interface, but he also points out, that one should make very careful use of the technique.

Also I did not know the term "fluent interface" before, we realized, that we already used this in the eZ components, to be more exact, in our Database package, which gives you a quite good ammount of SQL abstraction.

Here is a small example, that creates an SQL query to fetch data from the table "Person":

$q = $db->createSelectQuery(); $q->select( '*' ) ->from( 'Person' ) ->where( $q->expr->gt( 'age', 15 ) ) ->orderBy( 'full_name' ) ->limit( 10 ); $stmt = $q->prepare(); $stmt->execute();

As you can see, after creating a query object, we can manipulate the query it represents through a "fluent interface". After we chose what to select and from which table, we add a WHERE condition which indicates that we search for persons older than 15 years. After that we determine to order the results by the column "full_name". The last call in our "method chain" limits the number of results to 10. Surely in combination with our PersistantObject package (which allows you to store arbitrary data structures into database tables), this is a mighty tool to build very portable applications. And I asume you noticed it's relation to PDO. ;)

Of course, this is only a very small part in the eZ components, where we use a "fluent interface", but I'm absolutly sure, that it makes great sense in this place. The usage is very comfortable and the resulting code is nicely readable. I'm sure, this is a sensible place for a "fluent interface".

P.S.: If you want to see another cool (but not really fluent) interface, take a look at the ezcConsoleTable class. ;)

If you liked this blog post or learned something, please consider using flattr to contribute back: .



Add new comment

Fields with bold names are mandatory.