Created
November 10, 2012 00:46
-
-
Save jasonhazel/4049284 to your computer and use it in GitHub Desktop.
Unprovoked rewrite of Schwippy Tree script.
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 | |
// create the light controller and assign the color codes. | |
$lights = new LightController( | |
//-- our color codes | |
array( | |
'blue' => 'G5', | |
'white' => 'G6', | |
'green' => 'G7', | |
'red' => 'G8' | |
) | |
); | |
// 'fluent' interface. We can just string things together here. | |
// $lights->green('off')->green('on')->white('on')->red('off'); | |
// | |
// or, to make it a little more readable. | |
// $lights->green('off') | |
// ->green('on') | |
// ->white('on') | |
// ->red('off'); | |
// | |
// BUT, we're going to do it as a simple API. | |
// another way to do this would be for urls like: | |
// light_controller.php?red=on&blue=off | |
// doing it this way will allow us to specify several colors/states at once. | |
// could be used for an animation. | |
if (!empty($_GET)) { | |
foreach ($_GET as $color => $state) | |
$lights->{$color}($state); | |
} | |
// this will result in the API url being: light_controller.php?color=red&state=on | |
// if (isset($_GET['color']) && isset($_GET['state'])) { | |
// $lights->{$_GET['color']}($_GET['state']); | |
// } | |
// here is the magic. | |
// "something about dragons below" | |
class LightController | |
{ | |
private $_colors = array(); | |
private $_states = array('on', 'off'); | |
public function __construct(array $colors=array()) | |
{ | |
$this->_colors = $colors; | |
} | |
public function __call($color, $arguments) | |
{ | |
$state = $arguments[0]; | |
// check for a valid color and a valid state | |
if (in_array($state, $this->_states) AND array_key_exists($color, $this->_colors)) | |
// do work | |
$this->send($color, $state); | |
return $this; | |
} | |
private function send($color, $state) | |
{ | |
// compile the command string | |
$command = sprintf('heyu %s %s', | |
$state, | |
$this->_colors[$color] | |
); | |
passthru($command); | |
// you could also echo something out here. | |
// It would be display (or returned in your ajax call) | |
echo sprintf('The color %s has been turned %s (using "%s")', $color, $state, $command); | |
return $this; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment