Last active
October 14, 2018 18:24
-
-
Save mooror/cdc3595b451f0660d338172ee56b2a4f to your computer and use it in GitHub Desktop.
Proposal for iteratable/non-iteratable abstraction via callbacks (in php)
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 | |
class Person { | |
protected $name; | |
protected $age; | |
public function __construct($name, $age){ | |
$this->name = $name; | |
$this->age = $age; | |
} | |
public function getName(){ | |
return $this->name; | |
} | |
public function getAge(){ | |
return $this->age; | |
} | |
} | |
class Tester { | |
// Array of all test objects | |
protected $testObjects; | |
public function __construct(array $data){ | |
$testObjArray = array(); | |
foreach($data as $key => $value){ | |
$testObj = new Person($key, $value); | |
$testObjArray[] = $testObj; | |
} | |
$this->testObjects = $testObjArray; | |
} | |
public function setTestObjects(array $objArray){ | |
$this->testObjects = $objArray; | |
} | |
public function getTestObjects(){ | |
return $this->testObjects; | |
} | |
public function runTest($data, callable $onceCallback = NULL, callable $loopCallback = NULL){ | |
$testData = $this->getTestObjects(); | |
$dataArray = array(); | |
$isList = count($testData) > 1; | |
$isItem = count($testData) === 1; | |
$dataArray["isList"] = $isList; | |
$dataArray["isItem"] = $isItem; | |
$dataArray["extraData"] = $data; | |
// Call once | |
if($onceCallback !== NULL){ | |
$onceCallback($testData, $dataArray); | |
} | |
// If there is more then one test object | |
// Run the callback inside a loop | |
if($loopCallback !== NULL){ | |
if($isList){ | |
echo "Multiple items detected <br />"; | |
foreach($testData as $item){ | |
$loopCallback($item, $data); | |
} | |
// Otherwise run the function once | |
}else if($isItem){ | |
echo "Single item detected <br />"; | |
$loopCallback($testData[0], $data); | |
} | |
} | |
} | |
} | |
// Create a list of people we want to create | |
$people = array( | |
"John Doe" => "21", | |
"Jane Doe" => "22" | |
); | |
$extraData = "Just an extra string"; | |
$onceCallback = function($testData, $data){ | |
echo $data["extraData"]."<br />"; | |
}; | |
$loopCallback = function($item, $data){ | |
echo $item->getName()." : ".$item->getAge()."<br />"; | |
}; | |
// Pass that list into the tester | |
$personClassTester = new Tester($people); | |
$personClassTester->runTest($extraData, $onceCallback, $loopCallback); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment