PHP code example of phpoption / phpoption

1. Go to this page and download the library: Download phpoption/phpoption 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/ */

    

phpoption / phpoption example snippets


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();
    }
}

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());

return $this->findSomeEntity()
    ->orElse($this->findSomeOtherEntity())
    ->orElse($this->createEntity());

return $this->findSomeEntity()
    ->orElse(new LazyOption(array($this, 'findSomeOtherEntity')))
    ->orElse(new LazyOption(array($this, 'createEntity')));