Created
March 8, 2012 12:55
-
-
Save t10u/2000875 to your computer and use it in GitHub Desktop.
Traits - decorator pattern
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 | |
interface IDecoratedText | |
{ | |
public function __toString(); | |
} | |
trait TextDecorator | |
{ | |
protected $text = null; | |
public function __construct(IDecoratedText $text) | |
{ | |
$this->text = $text; | |
} | |
} | |
class Text implements IDecoratedText | |
{ | |
private $_str = 'World'; | |
public function __construct($str = '') | |
{ | |
if ($str != '') { | |
$this->_str = $str; | |
} | |
} | |
public function __toString() | |
{ | |
return sprintf('Hello, %s!', $this->_str); | |
} | |
} | |
class HtmlText implements IDecoratedText | |
{ | |
use TextDecorator; | |
public function __toString() | |
{ | |
return sprintf('<b>%s</b>', $this->text->__toString()); | |
} | |
} | |
class JsonDecorator implements IDecoratedText | |
{ | |
use TextDecorator; | |
public function __toString() | |
{ | |
return json_encode($this->text->__toString()); | |
} | |
} | |
$text = new Text(); | |
$text = new HtmlText($text); | |
$text = new JsonDecorator($text); | |
echo $text; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment