Skip to content

Instantly share code, notes, and snippets.

@justinyost
Last active April 21, 2016 16:35
Show Gist options
  • Save justinyost/5896b0bf8f813271b8546fa82c243240 to your computer and use it in GitHub Desktop.
Save justinyost/5896b0bf8f813271b8546fa82c243240 to your computer and use it in GitHub Desktop.
Swapping an anonymous function call with an Invoke Class
$collection = $itemCollection
->map(new EnsureIsItem());
class EnsureIsItem {
/**
* Construct a new instance of the class.
*/
public function __construct() {
}
/**
* Ensures a passed Item, is either an instance of Item or creates an instance
* using the passed in array data. This is intended to be called as part of a
* Collection based map operation like so.
*
* $collection->map(new EnsureIsItem());
*
* @param multi $item Either an instance of the Entity/Item class or an array
* from which we can construct a new instance.
* @param int $key The current key for the item in the Collection.
* @return \App\Model\Entity\Item Returns either the passed instance of Item
* or returns a new Instance.
*/
public function __invoke($item, $key) {
if (!($item instanceof Item)) {
$item = new Item($item);
}
return $item;
}
}
$ensureIsItem = function ($item, $key) {
if (!($item instanceof Item)) {
$item = new Item($item);
}
return $item;
};
$collection = $itemCollection
->map($ensureIsItem);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment