Skip to content

Instantly share code, notes, and snippets.

@t10u
Created March 8, 2012 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t10u/2000875 to your computer and use it in GitHub Desktop.
Save t10u/2000875 to your computer and use it in GitHub Desktop.
Traits - decorator pattern
<?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