Created
May 9, 2016 16:43
-
-
Save thinkingserious/1e16f633ede82d081eea40a4d32e1392 to your computer and use it in GitHub Desktop.
Fluent Interface in PHP Using Method Chaining and Reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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