Skip to content

Instantly share code, notes, and snippets.

@hello-josh
Created August 20, 2015 19:01
Show Gist options
  • Save hello-josh/3a2a3e7e0e12237e7af0 to your computer and use it in GitHub Desktop.
Save hello-josh/3a2a3e7e0e12237e7af0 to your computer and use it in GitHub Desktop.
Command Pattern implementation using Anonymous functions instead of objects
<?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
@hello-josh
Copy link
Author

$ php command-pattern.php
The light is on
the light is off

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment