In my last article I wrote about the new Lambda functions of PHP 5.3. Today I will talk about another cool feature. Since PHP version 5.3 it is possible to let functions return objects. This makes chaining like in JavaScript possible.
It is fairly simple: the function just has to return $this in the end and the next function can be added via ->.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class sqlChaining{ private $mpQuery = array(); ... public function from(array $mpTableNames){ $this->mpQuery[] = 'FROM'; $this->mpQuery[] = implode(',', $mpTableNames); return $this; } public function where(array $mpValues, $mode = self::MODE_AND){ $this->mpQuery[] = 'WHERE'; $this->{'_'.$mode}($mpValues); return $this; } ... } |
The whole construct can be used like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$sql = new sqlChaining(); $queryString = $sql->select(array( 'value1', 'value2', 'value3' ), 'DISTINCT')->from(array( 'tbl_test1', 'tbl_test2' ))->where(array( 'test' => 'test', 'test3' => 5 ))->_or(array( 'test5' => 'test3' ))->_and(array( 'test123' => '234' ))->getQueryString(); |
You can download the full example code here.
For now the functionality of my chaining class is really simple, but it can easily be extended to do more than just building the query string.
In my opinion chaining is most useful in two specific situations:
- like in my example for building strings
- for filling a data class with data like in other examples.