Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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