This package implements the Option type for PHP!
The Option type is intended for cases where you sometimes might return a value (typically an object), and sometimes you might return a base value (typically null) depending on arguments, or other runtime factors.
Often times, you forget to handle the case where a base value should be returned. Not intentionally of course, but maybe you did not account for all possible states of the system; or maybe you indeed covered all cases, then time goes on, code is refactored, some of these your checks might become invalid, or incomplete. Suddenly, without noticing, the base value case is not handled anymore. As a result, you might sometimes get fatal PHP errors telling you that you called a method on a non-object; users might see blank pages, or worse.
On one hand, the Option type forces a developer to consciously think about both cases (returning a value, or returning a base value). That in itself will already make your code more robust. On the other hand, the Option type also allows the API developer to provide more concise API methods, and empowers the API user in how he consumes these methods.
Installation is super-easy via Composer:
$ composer require phpoption/phpoption
or add it by hand to your composer.json
file.
class MyRepository
{
public function findSomeEntity($criteria): \PhpOption\Option
{
if (null !== $entity = $this->em->find(...)) {
return new \PhpOption\Some($entity);
}
// We use a singleton, for the None case.
return \PhpOption\None::create();
}
}
If you are consuming an existing library, you can also use a shorter version
which by default treats null
as None
, and everything else as Some
case:
class MyRepository
{
public function findSomeEntity($criteria): \PhpOption\Option
{
return \PhpOption\Option::fromValue($this->em->find(...));
// or, if you want to change the none value to false for example:
return \PhpOption\Option::fromValue($this->em->find(...), false);
}
}
$entity = $repo->findSomeEntity(...)->get(); // returns entity, or throws exception
$entity = $repo->findSomeEntity(...)->getOrElse(new Entity());
// Or, if you want to lazily create the entity.
$entity = $repo->findSomeEntity(...)->getOrCall(function() {
return new Entity();
});
// Before
$entity = $this->findSomeEntity();
if (null === $entity) {
throw new NotFoundException();
}
echo $entity->name;
// After
echo $this->findSomeEntity()->get()->name;
// Before
try {
$entity = $this->findSomeEntity();
} catch (NotFoundException $ex) {
$entity = new Entity();
}
// After
$entity = $this->findSomeEntity()->getOrElse(new Entity());
// Before
$entity = $this->findSomeEntity();
if (null === $entity) {
return new Entity();
}
return $entity;
// After
return $this->findSomeEntity()->getOrElse(new Entity());
If you'd like to try multiple alternatives, the orElse
method allows you to
do this very elegantly:
return $this->findSomeEntity()
->orElse($this->findSomeOtherEntity())
->orElse($this->createEntity());
The first option which is non-empty will be returned. This is especially useful with lazy-evaluated options, see below.
The above example has the flaw that we would need to evaluate all options when the method is called which creates unnecessary overhead if the first option is already non-empty.
Fortunately, we can easily solve this by using the LazyOption
class:
return $this->findSomeEntity()
->orElse(new LazyOption(array($this, 'findSomeOtherEntity')))
->orElse(new LazyOption(array($this, 'createEntity')));
This way, only the options that are necessary will actually be evaluated.
Of course, performance is important. Attached is a performance benchmark which
you can run on a machine of your choosing. The overhead incurred by the Option
type comes down to the time that it takes to create one object, our wrapper,
and one additional method call to retrieve the value from the wrapper. Unless
you plan to call a method thousands of times during a request, there is no
reason to stick to the object|null
return value; better give your code some
options!
If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. You may view our full security policy here.
PHP Option Type is licensed under Apache License 2.0.
Available as part of the Tidelift Subscription
The maintainers of phpoption/phpoption
and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.