Created
November 8, 2022 12:43
-
-
Save sagittaracc/2b42d3553adff961c58d8a646399f264 to your computer and use it in GitHub Desktop.
How to make a cup of tea =)
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 | |
$cup = new Cup(250); | |
$spoon = new Spoon(); | |
$someWater = new Water(250); | |
$sugar = new Sugar(); | |
$cup->put($sugar); | |
$cup->put($spoon); | |
$cup->poor($someWater); | |
$spoon->stir(); | |
// --------------------------------------- | |
class BaseObject | |
{ | |
private $children; | |
private $parent; | |
public function put(BaseObject $object) | |
{ | |
$this->children[] = $object; | |
$object->parent = $this; | |
} | |
public function getChildren() | |
{ | |
return $this->children; | |
} | |
public function getParent() | |
{ | |
return $this->parent; | |
} | |
public function move() | |
{ | |
} | |
} | |
class Food extends BaseObject | |
{ | |
} | |
class Sugar extends Food | |
{ | |
} | |
class Water extends BaseObject | |
{ | |
private $volume; | |
public function __construct($volume) | |
{ | |
$this->volume = $volume; | |
} | |
public function getVolume() | |
{ | |
return $this->volume; | |
} | |
} | |
class DinnerObject extends BaseObject | |
{ | |
} | |
class Spoon extends DinnerObject | |
{ | |
public function stir() | |
{ | |
parent::move(); | |
$parent = $this->getParent(); | |
if ($parent instanceof Cup) { | |
if ($parent->isFilled()) { | |
$children = $parent->getChildren(); | |
$canStir = false; | |
foreach ($children as $child) { | |
if ($child instanceof Sugar) { | |
$canStir = true; | |
} | |
} | |
if (!$canStir) { | |
throw new Exception("There is no sugar!"); | |
} | |
} | |
else { | |
throw new Exception("The cup is not filled!"); | |
} | |
} | |
else { | |
throw new Exception("Can't stir"); | |
} | |
} | |
} | |
class Cup extends DinnerObject | |
{ | |
private $volume; | |
private $filled; | |
public function __construct($volume) | |
{ | |
$this->volume = $volume; | |
$this->filled = false; | |
} | |
public function isFilled() | |
{ | |
return $this->filled; | |
} | |
public function poor(Water $water) | |
{ | |
if ($water->getVolume() >= $this->volume) { | |
$this->filled = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment