Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fluent Interface in PHP Using Method Chaining and Reflection
<?php
class Fluent {
function __construct($cache) {
$this->cache = ($cache ? $cache : []);
}
// Build the cache, and handle special cases
public function _($name) {
array_push($this->cache, $name);
return new Fluent($this->cache);
}
// Final method call
public function method() {
return $this->cache;
}
// Reflection
public function __call($name, $args) {
return $this->_($name);
}
}
$fluent = new Fluent;
$chain = $fluent->hello()->world();
print_r($chain->method());
// 'for' demonstrates handling special cases
$new_chain = $chain->thanks()->_("for")->all()->the()->fish();
print_r($new_chain->method());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.