Fluent Interfaces in PHP5

Fluent Interfaces in PHP5

In PHP 5 terms, a fluent interface to an object is one where the setter methods return an object handle. It is perhaps simplest to always return $this, however any object handle can be returned. Here’s a simple PHP class that demonstrates how a fluent interface is built:

<?php
class Fluent {
public function hello() {
echo ‘hello ‘;
return $this;
}

public function world() {
echo ‘world’;
return $this;
}
}
$fluent = new Fluent();
$fluent->hello()
->world();
?>

The code above will output hello world. As you can see, a fluent interface is quite easy to implement.
This buzzword fluent interfaces is a way of chaining methods of an object together. By having a method return a reference to the object itself, return $this; you chain methods together like this $this->methodOne()->methodTwo()->methodThree();. This can make your code easier to read, and that is the point of using fluent interfaces, making your code easier to read.

The first example is a snippet from a class in which the method makeNormal() is used to create an order in the system. The makeNormal() method is part of the order object.

<?php
private function makeNormal(Customer $customer) {
$o1 = new Order();
$customer->addOrder($o1);
$line1 = new OrderLine(6, Product::find('TAL'));
$o1->addLine($line1);
$line2 = new OrderLine(5, Product::find('HPK'));
$o1->addLine($line2);
$line3 = new OrderLine(3, Product::find('LGV'));
$o1->addLine($line3);
$line2->setSkippable(true);
$o1->setRush(true);
}
?>

Next, they show the fluent interface version of the code.

<?php
private function makeFluent(Customer $customer) {
$customer->newOrder()
->with(6, 'TAL')
->with(5, 'HPK')->skippable()
->with(3, 'LGV')
->priorityRush();
}
?>

As you can see, the second example is easier to read, assuming you understand that the with() method adds lines to the order. As stated earlier, this bit of magic is accomplished by the with(), skippable(), and priorityRush() methods retuning a reference to the object. ($this) That is the one and only secret to fluent interfaces.

Leave a Reply


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.