PHP code example of sanmai / later

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

    

sanmai / later example snippets


use function Later\later;

$deferred = later(function () {
    $deepThought = new DeepThought();
    $deepThought->solveTheQuestion();

    yield $deepThought;
});

$deferred->get()->getAnswer(); // 42
$deferred->get()->getAnswer(); // same 42

use Later\Interfaces\Deferred;
use function Later\lazy;

final class HyperIntelligentMice
{
    /** @var Deferred<DeepThought> */
    private $supercomputer;

    public function __construct(DeepThought $deepThought)
    {
        $this->supercomputer = lazy(self::updateDeepThought($deepThought));
    }

    /** @return iterable<DeepThought> */
    private static function updateDeepThought(DeepThought $deepThought): iterable
    {
        $deepThought->solveTheQuestion();

        yield $deepThought;
    }

    public function getAnswer(): int
    {
        return $this->supercomputer->get()->getAnswer();
    }
}

use function Later\now;

$deferred = now($result);
$deferred->get(); // returns $result

use function Later\lazy;

$this->lazyDependency = lazy([
    $myDependency,
]);

use function Later\now;

$this->lazyDependency = now($myDependency);

$deferredMock = $this->createMock(\Later\Interfaces\Deferred::class);
$deferredMock
    ->expects($this->once())
    ->method('get')
    ->willReturn($myDependency)
;
diff
 private function makeFooBar()
 {
    //...

-    return $foo;
+    yield $foo;
 }
diff
 use function Later\lazy;

 public function __construct()
 {
-    $this->fooBar = $this->makeFooBar();
+    $this->lazyFooBar = lazy($this->makeFooBar());
 }

 public function usesFooBar()
 {
     if ($fooBarReallyRequired) {
-        $this->fooBar->getResult();
+        $this->lazyFooBar->get()->getResult();
     }
 }