Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Last active July 19, 2017 10:42
Show Gist options
  • Save nezarfadle/f1d5a458372939f20a37ea004c95587f to your computer and use it in GitHub Desktop.
Save nezarfadle/f1d5a458372939f20a37ea004c95587f to your computer and use it in GitHub Desktop.
<?php

class CacheDecorater
{
    function decorate( $tweet )   
    {
        $tweet->cached = true;
        return $tweet;
    }
}

class UrlDecorater
{
    function decorate( $tweet )   
    {
        $tweet->url = "http://localhost/tweets/$tweet->id";
        return $tweet;
    }
}

class TwitterGateway
{
    
    protected $deocraters;
    
    function andThen($decorater)
    {
        $this->decoraters[] = $decorater;
        return $this;
    }
    
    function get()
    {
        $data = [
            (object)['id' => 1, 'text' =>  'Tweet 1'],
            (object)['id' => 2, 'text' =>  'Tweet 2'],
        ];
        
        foreach($data as &$tweet)
        {
            foreach($this->decoraters as $decorater)
            {
                $tweet = $decorater->decorate( $tweet );
            }
        }
        
        
        return $data;
    }
    
}

$twitter = new TwitterGateway();
$tweets = $twitter->andThen( new CacheDecorater() )
                  ->andThen( new UrlDecorater() )
                  ->get();
                  
print_r( $tweets );

/** Output

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [text] => Tweet 1
            [cached] => 1
            [url] => http://localhost/tweets/1
        )

    [1] => stdClass Object
        (
            [id] => 2
            [text] => Tweet 2
            [cached] => 1
            [url] => http://localhost/tweets/2
        )

)

**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment