1. Go to this page and download the library: Download unicorn-fail/php-option library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
unicorn-fail / php-option example snippets
use UnicornFail\PhpOption\None;
use UnicornFail\PhpOption\Some;
class MyRepository
{
public function findSomeEntity($criteria)
{
if (null !== $entity = $this->entityManager->find($criteria)) {
return Some::create($entity);
}
// Use a singleton for the None case (it's statically cached for performance).
return None::create();
}
}
use UnicornFail\PhpOption\Option;
class MyRepository
{
public function findSomeEntity($criteria)
{
return Option::create($this->entityManager->find($criteria));
// Or, if you want to change the none value to false for example:
return Option::create($this->em->find($criteria), ['noneValue' => false]);
}
}
$entity = $repo->findSomeEntity($criteria)->get(); // Returns an Entity, or throws exception.
$entity = $repo->findSomeEntity($criteria)->getOrElse(new Entity);
// Or, if you need to lazily create the entity.
$entity = $repo->findSomeEntity($criteria)->getOrCall(function() {
return new Entity;
});
$entity = $this->findSomeEntity();
if ($entity === null) {
throw new NotFoundException();
}
return $entity->name;