Skip to content

Instantly share code, notes, and snippets.

@davialexandre
Created October 31, 2016 13:25
Show Gist options
  • Save davialexandre/6df1ac26450563cf59ac294a9bc5987e to your computer and use it in GitHub Desktop.
Save davialexandre/6df1ac26450563cf59ac294a9bc5987e to your computer and use it in GitHub Desktop.
Visitor pattern example
<?php
class CSVAbsenceTypeCleaner extends CSVCleanerVisitor {
public function visit(array $row) {
$this->deleteRecord('HRAbsenceType', ['name' => $row['name']]);
}
}
<?php
class CSVAbsenceTypeImporter extends CSVImporterVisitor {
function importRecord(array $row) {
// code specific to import absence type here
}
public function visit(array $row) {
$this->importRecord($row);
}
}
<?php
abstract class CSVCleanerVisitor implements CSVProcessingVisitor {
protected function deleteRecord($entity, $searchParams) {
//code to delete record here
}
}
<?php
abstract class CSVImporterVisitor implements CSVProcessingVisitor {
abstract function importRecord(array $row);
}
<?php
interface CSVProcessingVisitor {
public function visit(array $row);
}
<?php
class CSVProcessor {
private $fileHandler;
public function __construct(SplFileObject $file) {
$this->fileHandler = $file;
}
public function process(CSVProcessingVisitor $visitor) {
$header = null;
while (!$this->fileHandler->eof()) {
$row = $this->fileHandler->fgetcsv();
if ($header === null) {
$header = $row;
continue;
}
$row = array_combine($header, $row);
$visitor->visit($row);
}
}
}
<?php
$file = new SplFileObject('absence_type.csv');
$processor = new CSVProcessor($file);
// Clean things
$absenceTypeCleaner = new CSVAbsenceTypeCleaner();
$processor->process($absenceTypeCleaner);
//Import things
$absenceTypeImporter = new CSVAbsenceTypeImporter();
$processor->process($absenceTypeImporter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment