Skip to content

Instantly share code, notes, and snippets.

@thinkingserious
Created May 9, 2016 16:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkingserious/1e16f633ede82d081eea40a4d32e1392 to your computer and use it in GitHub Desktop.
Save thinkingserious/1e16f633ede82d081eea40a4d32e1392 to your computer and use it in GitHub Desktop.
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