laze is a PHP library designed for defining lazy evaluation. Values are set as closures and only materialize upon first access, ensuring efficient and controlled initialization. Once a closure function is evaluated, it becomes immutable and cannot be redefined as a different value. However, it can be redefined as a closure until it’s accessed, at which point it transforms into a non-closure value.
Laze provides lazy immutable values for PHP. You define a key with a closure, and the value is computed on first read and then cached.
- PHP 8.0 or higher
composer require divengine/laze<?php
require 'vendor/autoload.php';
use divengine\laze;
laze::define('APP_NAME', fn () => 'Laze Demo');
echo laze::read('APP_NAME');laze::define($key, $callable)registers a lazy value.laze::read($key)evaluates once and returns the stored value.laze::defined($key)checks if a key exists.laze::evaluated($key)checks if a key was evaluated (throws if undefined).laze::constraint($name, $checker)validates values on evaluation.
You can redefine a value before it is evaluated. After the first read, the
value becomes immutable and further define calls are ignored.
<?php
laze::define('FOO', fn () => 1);
laze::define('FOO', fn () => 2);
echo laze::read('FOO'); // 2
laze::define('FOO', fn () => 3);
echo laze::read('FOO'); // still 2<?php
laze::constraint(
'APP_PORT must be an int',
fn ($key, $value) => $key === 'APP_PORT' ? is_int($value) : true
);
laze::define('APP_PORT', fn () => 8080);Constraints run when a value is evaluated. If a constraint returns false,
read throws an exception.
Laze stores state statically. You can reset it between tests with reflection:
<?php
use divengine\laze;
$reflection = new ReflectionClass(laze::class);
$store = $reflection->getProperty('store');
$store->setAccessible(true);
$store->setValue(null, []);
$constraints = $reflection->getProperty('constraints');
$constraints->setAccessible(true);
$constraints->setValue(null, []);
$evaluated = $reflection->getProperty('evaluated');
$evaluated->setAccessible(true);
$evaluated->setValue(null, []);Or run PHPUnit with process isolation:
vendor/bin/phpunit --process-isolationSee docs/README.md for guides and FAQ.
This project is licensed under the GNU General Public License. See LICENSE.
Contributions are welcome. Please open an issue or submit a pull request.
Laze is developed and maintained by Divengine Software Solutions.