repl.it
@jonathanbell/

Decorator in PHP

PHP CLI

No description

fork
loading
Files
  • main.php
main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php

/**
 * Decorators
 */

interface CarService {

  public function getCost();

  public function getDescription();

}

class BasicInspection implements CarService {

  const COST = 25;

  public function getCost() {
    return self::COST;
  }

  public function getDescription() {
    return 'basic inspection';
  }

}

class OilChange implements CarService {

  const COST = 29;

  /**
   * The CarService dependency.
   *
   * @var CarService
   */
  protected $carService;

  function __construct(CarService $carService) {
    $this->carService = $carService;
  }

  public function getCost() {
    return self::COST + $this->carService->getCost();
  }

  public function getDescription() {
    return $this->carService->getDescription().', and oil change';
  }

}

class TireRotation implements CarService {

  const COST = 11;

  protected $carService;

  function __construct(CarService $carService) {
    $this->carService = $carService;
  }

  public function getCost() {
    return self::COST + $this->carService->getCost();
  }

  public function getDescription() {
    return $this->carService->getDescription().', and tire rotation';
  }

}

// We must pass CarService to the $oilChange
$basicInspection = new BasicInspection();
$oilChange = new OilChange($basicInspection);
echo $oilChange->getCost();
echo PHP_EOL;

// We can also pass multiple services to each other
echo (new TireRotation(new OilChange(new BasicInspection())))->getCost();
echo PHP_EOL;

// Getting the service description for two services via a decorator
$service = new TireRotation(new BasicInspection);
echo $service->getDescription();
echo PHP_EOL;

// What about 3 services..? or more!
$service = new OilChange(new TireRotation(new BasicInspection()));
echo 'The total cost of your '.$service->getDescription().' is '.$service->getCost().'.';
echo PHP_EOL;