Box class Box { protected $value; public static function of($value) { return new static($value); } public function __construct($value) { $this->value = $value; } public function map(callable $f) : Box { return new static($f($this->value)); } public function fold(callable $f = null) { return $f ? $f($this->value) : $this->value; } }
A better way... $maybeUser = Eloquent::maybeFind(9001); $something = $maybeUser->map(function($user) { return SomeObject::someTransformationLol($user); }); // Later in the app function process(Maybe $maybeData) { return $maybeData->fold(function($value) { // If you need to do a side-effect dependent on if null // Could finally check here }); }
You don’t like closures? class ConvertToTruth { public function convert($text) { return str_replace('the cloud', “someone else's computer", $text); } public function __invoke($text) { return $this->convert($text); } }
You don’t like closures? collect(["My data lives in the cloud"]) ->map(new ConvertToTruth) ->toArray() // [“My data lives in someone else’s machine”] // or Box::of(“My data lives in the cloud") ->map(new ConvertToTruth) ->fold() // My data lives in someone else’s machine