Created
September 12, 2012 23:27
-
-
Save marekkalnik/3710733 to your computer and use it in GitHub Desktop.
It's just a view - code sample
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 | |
abstract class TableDataFormatter | |
{ | |
protected $columnConfiguration; | |
public function __construct(array $columnConfiguration) | |
{ | |
$this->columnConfiguration = $columnConfiguration; | |
} | |
public function addData(array $data) | |
{ | |
foreach ($data as $result) { | |
$values = array(); | |
foreach ($this->columnConfiguration as $columnNumber => $columnDef) { | |
$values[] = $this->getColumnValue($result, $columnDef); | |
} | |
$this->addRow($values); | |
} | |
} | |
protected function getColumnValue($item, $columnDef) | |
{ | |
return $item->{$columnDef['getter']}(); | |
} | |
abstract protected function addRow(array $cellValues); | |
} | |
class HtmlTableDataFormatter extends TableDataFormatter | |
{ | |
protected function addRow(array $cellValues) | |
{ | |
$this->output .= '<tr>'; | |
foreach ($cellValues as $value) { | |
$this->output .= '<td>' . $value . '</td>'; | |
} | |
$this->output .= '</tr>'; | |
} | |
public function getOutput() | |
{ | |
return $this->output; | |
} | |
} | |
class ExcelTableDataFormatter extends TableWriter | |
{ | |
private $lastColumn = 0; | |
private $lastRow = 0; | |
private $excelWriter; | |
public function __construct($columnConfiguration, $excelWriter) | |
{ | |
$this->excelWriter = $excelWriter; | |
parent::__construct($columnConfiguration); | |
} | |
protected function addRow(array $cellValues) | |
{ | |
$row = $this->getNextRow(); | |
$worksheet = $this->excelWriter->getActiveSheet(); | |
foreach ($cellValues as $value) { | |
$worksheet->setCellValueByColumnAndRow($this->getNextColumn(), $row, $value); | |
} | |
} | |
public function getNextRow() | |
{ | |
$this->lastColumn = 0; | |
return $this->lastRow++; | |
} | |
public function getNextColumn() | |
{ | |
return $this->lastColumn++; | |
} | |
public function getOutput() | |
{ | |
$this->excelWriter->save($this->getFilename()); | |
return $this->getFilename(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment