- str_repeat: documentation ( source)
- json_encode: documentation ( source)
- define: documentation ( source)
<?php
define("TYPE", "JSON");
abstract class View
{
protected $imp;
public function __construct()
{
if (TYPE == 'CLI')
$this->imp = new ViewImplCli();
else if (TYPE == 'JSON')
$this->imp = new ViewImplJson();
else
throw new Exception('Unknown environment');
}
public function addText($text)
{
return $this->imp->addText($text);
}
public function addLine()
{
return $this->imp->addLine();
}
public function getResult()
{
print $this->imp->getResult();
}
}
class ViewContent extends View
{
public function printParagraph($text)
{
$this->addText($text);
}
}
class ViewTable extends View
{
public function addCell($text)
{
$this->addLine();
$this->addText($text);
$this->addLine();
}
}
abstract class ViewImpl
{
abstract public function addText($text);
abstract public function addLine();
abstract public function getResult();
}
class ViewImplCli extends ViewImpl
{
protected $result = "";
public function addLine()
{
$this->result .= str_repeat('-', 80).PHP_EOL;
}
public function addText($text)
{
$this->result .= $text.PHP_EOL;
}
public function getResult()
{
return $this->result;
}
}
class ViewImplJson extends ViewImpl
{
protected $result = array();
public function addLine()
{
$this->result[] = array('type' => 'line');
}
public function addText($text)
{
$this->result[] = array('type' => 'text', 'text' => $text);
}
public function getResult()
{
return json_encode($this->result);
}
}
$content = new ViewContent();
$content->printParagraph('Hello world');
echo $content->getResult();
$table = new ViewTable();
$table->addCell('Hello world in cell');
echo $table->getResult();