Skip to content

Instantly share code, notes, and snippets.

@johnkary
Last active August 29, 2015 14:16
Show Gist options
  • Save johnkary/a64363bac55c90a1ca97 to your computer and use it in GitHub Desktop.
Save johnkary/a64363bac55c90a1ca97 to your computer and use it in GitHub Desktop.
Example of using tuples instead of array key-value pairs
class BuildReport
{
private function getColumnHeaders()
{
// Why do you need array keys if this array is private details?
// It's never exposed outside this class so you have full control of its format
return [
['id' => 'first_name', 'label' => 'First Name'],
['id' => 'last_name', 'label' => 'Last Name'],
['id' => 'department', 'label' => 'Department'],
];
}
public function render($records)
{
foreach ($this->getColumnHeaders() as $header) {
$id = $header['id'];
$label = $header['label'];
// Do something with $id and label ...
}
}
}
class BuildReport
{
private function getColumnHeaders()
{
// If you need to change the data, the changes are confined to this class
return [
['first_name', 'First Name'],
['last_name', 'Last Name'],
['department', 'Department'],
];
}
public function render($records)
{
// PHP >= 5.5 -- This is the shortest thanks to this feature in 5.5 https://wiki.php.net/rfc/foreachlist
foreach ($this->getColumnHeaders() as list($id, $label)) {
// Do something with $id and label ...
}
// PHP < 5.5 -- This is slightly more code if you're running 5.4 or older
foreach ($this->getColumnHeaders() as $header) {
list($id, $label) = $header;
// Do something with $id and label ...
}
}
}
@jrmadsen67
Copy link

Perhaps this is a bad example, but what do you do when you later on you need to add meta-data to each of these? ex: a class name to certain headers

It seems to me the weakness of a tuple is that by its very definition it is hard-coded to be a pair. I ccan see other examples where this could be desirable - key:values where you might actually like to enforce that pairing, but if that is not the case, you seem to lock yourself into a structure purely because you feel it "looks like nicer code"

Have I completely missed your point?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment