fork download
  1. <?php
  2. abstract class Coffee {
  3. private $coffeeComponents = [];
  4.  
  5. public function addComponent(ICoffeeComponent $component) {
  6. $type = get_class($component);
  7. $this->coffeeComponents[$type] = $component;
  8. }
  9.  
  10. protected function getComponent($type) { // Make public if you want access from outside, but you should not really.
  11. if (!is_string($type)) {
  12. $argType = is_object($type) ? get_class($type) : gettype($type);
  13. throw new InvalidArgumentException(
  14. get_class($this).'::getComponent expects parameter 1 to be string. '.$argType.' given.'
  15. );
  16. }
  17. if (!isset($this->coffeeComponents[$type])) {
  18. throw new InvalidArgumentException(get_class($this).' has no component: '.$type);
  19. }
  20.  
  21. return $this->coffeeComponents[$type];
  22. }
  23. }
  24.  
  25. interface ICoffeeComponent {
  26. // common interface here.
  27. }
  28.  
  29. class SugarCube implements ICoffeeComponent {
  30. // implement common interface.
  31.  
  32. // specific stuff.
  33. public function foo() {
  34. echo 'bar';
  35. }
  36. }
  37.  
  38. class Expresomix implements ICoffeeComponent {
  39. // implement common interface.
  40.  
  41. // specific stuff.
  42. }
  43.  
  44. class Beverage extends Coffee {
  45. public function foo() {
  46. $component = $this->getComponent('SugarCube');
  47. $component->foo();
  48. }
  49. }
  50.  
  51. $coffee = new Beverage();
  52.  
  53. $coffee->addComponent(new SugarCube());
  54. $coffee->addComponent(new Expresomix());
  55.  
  56. $coffee->foo();
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
bar