PHP code example of spatie / once

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

    

spatie / once example snippets


$myClass = new class() {
    public function getNumber(): int
    {
        return once(function () {
            return rand(1, 10000);
        });
    }
};

$myClass = new class() {
    public function getNumber(): int
    {
        return once(function () {
            return rand(1, 10000);
        });
    }
};

class MyClass
{
    /**
     * It also works in static context!
     */
    public static function getNumberForLetter($letter)
    {
        return once(function () use ($letter) {
            return $letter . rand(1, 10000000);
        });
    }
}

Spatie\Once\Cache::getInstance()->flush();

Spatie\Once\Cache::getInstance()->disable();

Spatie\Once\Cache::getInstance()->enable();

// config/octane.php

OperationTerminated::class => [
    FlushTemporaryContainerInstances::class,
    // DisconnectFromDatabases::class,
    // CollectGarbage::class,

    FlushSpatieOnce::class, // we should create this class we have added here
],

// app/Listeners/FlushSpatieOnce.php

use Spatie\Once\Cache;

class FlushSpatieOnce
{
    public function handle($event)
    {
        Cache::getInstance()->flush();
    }
}

$trace = debug_backtrace(
    DEBUG_BACKTRACE_PROVIDE_OBJECT, 2
)[1];

$backtrace = new Backtrace($trace);

$object = $backtrace->getObject();

$hash = $backtrace->getHash();

public function has(object $object, string $backtraceHash): bool
{
    if (! isset($this->values[$object])) {

        return false;
    }

    return array_key_exists($backtraceHash, $this->values[$object]);
}