Created
August 20, 2015 19:01
-
-
Save hello-josh/3a2a3e7e0e12237e7af0 to your computer and use it in GitHub Desktop.
Command Pattern implementation using Anonymous functions instead of objects
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 | |
/** | |
* Lamp object to be manipulated because a Lamp is a thing | |
*/ | |
class Lamp { | |
public function turn_on() { | |
echo 'The light is on' . PHP_EOL; | |
} | |
public function turn_off() { | |
echo 'the light is off' . PHP_EOL; | |
} | |
} | |
/** | |
* Returns the client to process commands for a lamp | |
* | |
* @param Lamp $lamp | |
* @return callable | |
*/ | |
function light_switch_client(Lamp $lamp) { | |
return function(callable $command) use ($lamp) { | |
return $command($lamp); | |
}; | |
} | |
## commands | |
/** | |
* Returns a command to turn a lamp on | |
* | |
* @return callable | |
*/ | |
function turn_on_command() { | |
return function (Lamp $lamp) { | |
$lamp->turn_on(); | |
}; | |
} | |
/** | |
* Returns a command to turn a lamp off | |
* | |
* @return callable | |
*/ | |
function turn_off_command() { | |
return function (Lamp $lamp) { | |
$lamp->turn_off(); | |
}; | |
} | |
$client = light_switch_client(new \Lamp()); | |
$client(turn_on_command()); // The light is on | |
$client(turn_off_command()); // The light is off |
Author
hello-josh
commented
Aug 20, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment