Skip to content

Instantly share code, notes, and snippets.

@ftdebugger
Last active December 28, 2015 10:19
Show Gist options
  • Save ftdebugger/7485984 to your computer and use it in GitHub Desktop.
Save ftdebugger/7485984 to your computer and use it in GitHub Desktop.
<?php
interface CommandInterface
{
public function execute();
}
class TurnOnCommand implements CommandInterface
{
/**
* @var Lamp
*/
protected $lamp;
/**
* @param Lamp $lamp
*/
public function __construct(Lamp $lamp)
{
$this->lamp = $lamp;
}
public function execute()
{
$this->lamp->turnOn();
}
}
class TurnOffCommand implements CommandInterface
{
/**
* @var Lamp
*/
protected $lamp;
/**
* @param Lamp $lamp
*/
public function __construct(Lamp $lamp)
{
$this->lamp = $lamp;
}
public function execute()
{
$this->lamp->turnOff();
}
}
class SosCommand implements CommandInterface
{
/**
* @var Lamp
*/
protected $lamp;
/**
* @param Lamp $lamp
*/
public function __construct(Lamp $lamp)
{
$this->lamp = $lamp;
}
private function signal($sleep)
{
$this->lamp->turnOn();
sleep($sleep);
$this->lamp->turnOff();
sleep($sleep);
}
public function execute()
{
while (true) {
for ($i = 0; $i < 3; $i++) {
$this->signal(0.1);
}
for ($i = 0; $i < 3; $i++) {
$this->signal(1);
}
}
}
}
class LampCommandFactory
{
public function factory($type, Lamp $lamp)
{
if ($type == 'ON') {
return new TurnOnCommand($lamp);
}
if ($type == 'OFF') {
return new TurnOffCommand($lamp);
}
if ($type == 'SOS') {
return new SosCommand($lamp);
}
throw new RuntimeException('Cannot produce command with type ' . $type);
}
}
class Lamp
{
public function turnOn()
{
echo "I'm bright and cheerful light.\n";
}
public function turnOff()
{
echo "I am quiet and peaceful shadow\n";
}
}
$lamp = new Lamp();
$factory = new LampCommandFactory();
$factory->factory($argv[1], $lamp)->execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment