Skip to content

Instantly share code, notes, and snippets.

@jadell
Created January 14, 2012 03:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jadell/1610148 to your computer and use it in GitHub Desktop.
Save jadell/1610148 to your computer and use it in GitHub Desktop.
Command invoker pattern
<?php
interface Command
{
public static function register();
public function execute();
}
class HelloCommand implements Command {
protected $name;
public static function register() {
return function ($name) {
return new HelloCommand($name);
};
}
public function __construct($name) {
$this->name = $name;
}
public function execute() {
echo "Hello, " . $this->name . "\n";
}
}
class PwdCommand implements Command {
public static function register() {
return function () {
return new PwdCommand();
};
}
public function execute() {
echo "You are here: " . getcwd() . "\n";
}
}
class CustomCommand implements Command {
protected $foo;
protected $bar;
public static function register() {
return function ($foo, $bar) {
return new CustomCommand($foo, $bar);
};
}
public function __construct($foo, $bar) {
$this->foo = $foo;
$this->bar = $bar;
}
public function execute() {
echo "What does it all mean? " . ($this->foo + $this->bar) . "\n";
}
}
class Invoker {
protected $commandMap = array();
public function __construct() {
$this->register('hello', 'HelloCommand');
$this->register('pwd', 'PwdCommand');
}
public function __call($command, $args) {
if (!array_key_exists($command, $this->commandMap)) {
throw new BadMethodCallException("$command is not a registered command");
}
$command = call_user_func_array($this->commandMap[$command], $args);
$command->execute();
}
public function register($command, $commandClass) {
if (!array_key_exists('Command', class_implements($commandClass))) {
throw new LogicException("$commandClass does not implement the Command interface");
}
$this->commandMap[$command] = $commandClass::register();
}
}
$invoker = new Invoker();
$invoker->hello('Josh');
$invoker->pwd();
$invoker->register('custom', 'CustomCommand');
$invoker->custom(40, 2);
$invoker->register('pwd', 'CustomCommand');
$invoker->pwd(2, 40);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment