Created
          November 3, 2015 03:27 
        
      - 
      
- 
        Save thoriqmacto/1435e65576b227f32df7 to your computer and use it in GitHub Desktop. 
    [PHP] Decorator Pattern Example
  
        
  
    
      This file contains hidden or 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 | |
| class CD { | |
| public $trackList; | |
| public function __construct(){ | |
| $this->trackList = array(); | |
| } | |
| public function addTrack($track){ | |
| $this->trackList[] = $track; | |
| } | |
| public function getTrackList(){ | |
| $output = ''; | |
| foreach ($this->trackList as $num=>$track){ | |
| $output .= ($num + 1) . ") {$track}. "; | |
| } | |
| return $output; | |
| } | |
| } | |
| class CDTrackListDecoratorCaps{ | |
| private $__cd; | |
| public function __construct(CD $cd){ | |
| $this->__cd = $cd; | |
| } | |
| public function makeCaps(){ | |
| foreach ($this->__cd->trackList as &$track){ | |
| $track = strtoupper($track); | |
| } | |
| } | |
| } | |
| $tracksFromExternalSource = array('What It Means', 'Brr', 'Goodbye'); | |
| $myCD = new CD(); | |
| foreach ($tracksFromExternalSource as $track) { | |
| $myCD->addTrack($track); | |
| } | |
| $myCDCaps = new CDTrackListDecoratorCaps($myCD); | |
| $myCDCaps->makeCaps(); | |
| print "The CD contains the following tracks: " . $myCD->getTrackList(); | |
| ?> | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment