PHP code example of php-architecture-kit / lazy-operators

1. Go to this page and download the library: Download php-architecture-kit/lazy-operators 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/ */

    

php-architecture-kit / lazy-operators example snippets


use PhpArchitecture\LazyOperators\Foundation\Expression\Arithmetic\Arithmetic;

$expr = Arithmetic::of(2)
    ->multiply(3)
    ->add(4)
    ->build();

$expr(); // 10 -- (2 * 3) + 4, computed only on this line

$base = Arithmetic::of(2)->add(3);

$timesFour = $base->multiply(4)->build();
$timesTen  = $base->multiply(10)->build();

$timesFour(); // 20 -- (2 + 3) * 4
$timesTen();  // 50 -- (2 + 3) * 10, $base itself was never changed

interface Expression
{
    public function __invoke(): mixed;
}

use PhpArchitecture\LazyOperators\Foundation\Expression\Decorator;
use PhpArchitecture\LazyOperators\Foundation\Expression\Expression;
use PhpArchitecture\LazyOperators\Foundation\Expression\ExpressionTreeConfig;

$config = ExpressionTreeConfig::decoratedBy(
    static fn (Expression $node): Decorator => new TracingDecorator($node, $logger),
);

Arithmetic::of(2, $config)->multiply(3)->add(4)->build();

// before 1.6.0 -- the IntLiteral(0) was a throwaway, and $logger never arrived
new ExpressionTreeConfig(new TracingDecorator(new IntLiteral(0), $logger));

// 1.6.0 onwards
ExpressionTreeConfig::decoratedBy(
    static fn (Expression $node): Decorator => new TracingDecorator($node, $logger),
);

use PhpArchitecture\LazyOperators\Foundation\Expression\Comparison\Comparison;
use PhpArchitecture\LazyOperators\Foundation\Expression\Conditional\Conditional;

$label = Conditional::if(Comparison::of($x)->greaterThan(10)->build())
    ->then('big')
    ->else('small')
    ->build();

$label(); // 'big' or 'small', depending on $x

use PhpArchitecture\LazyOperators\Foundation\Expression\Extension\Allocation\Allocation;
use PhpArchitecture\LazyOperators\Foundation\Expression\Extension\BcMath\BcMath;

// Native PHP: 0.1 + 0.2 === 0.30000000000000004
$amount = BcMath::add('0.1', '0.2', 1);

$result = Allocation::allocate($amount, [1, 1], 2)();
// [0.15, 0.15]

$allocation = Allocation::allocate(100, [1, 1, 1], 2);
$allocation->useBcMathIfAvailable = false; // force native floats
$allocation();