Created
April 26, 2017 07:42
-
-
Save avastamin/f4bd7d13a5349f1dc5f01f9845af9747 to your computer and use it in GitHub Desktop.
Chain Design Pattern in PHP
This file contains 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 | |
abstract class HomeChecker { | |
protected $succeesor; | |
public abstract function check(HomeStatus $home); | |
public function succeedWith(HomeChecker $succeesor){ | |
$this->succeesor = $succeesor; | |
} | |
public function next(HomeStatus $home){ | |
if ($this->succeesor){ | |
$this->succeesor->check($home); | |
} | |
} | |
} | |
class Locks extends HomeChecker { | |
public function check(HomeStatus $home) { | |
if (!$home->doorLocked){ | |
throw new Exception('Door is not locked! Abort abort!'); | |
} | |
$this->next($home); | |
} | |
} | |
class Alarm extends HomeChecker { | |
public function check(HomeStatus $home) { | |
if (!$home->lightsOn){ | |
throw new Exception('Lights is not off! Abort abort!'); | |
} | |
$this->next($home); | |
} | |
} | |
class Lights extends HomeChecker { | |
public function check(HomeStatus $home) { | |
if (!$home->alarmOn){ | |
throw new Exception('Alarm is not on! Abort abort!'); | |
} | |
$this->next($home); | |
} | |
} | |
class HomeStatus { | |
public $alarmOn = true; | |
public $lightsOn = false; | |
public $doorLocked = true; | |
} | |
$locks = new Locks; | |
$lights = new Lights; | |
$alarm = new Alarm; | |
$locks->succeedWith($lights); | |
$lights->succeedWith($alarm); | |
$locks->check(new HomeStatus); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment