Last active
April 21, 2016 16:35
-
-
Save justinyost/5896b0bf8f813271b8546fa82c243240 to your computer and use it in GitHub Desktop.
Swapping an anonymous function call with an Invoke Class
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
$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; | |
} | |
} |
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
$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