PHP code example of sdboyer / frozone

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

    

sdboyer / frozone example snippets



use Frozone\Freezable;
use Frozone\FreezableTrait;

class Counter implements Freezable {
    use FreezableTrait;

    protected $callcount = 0;

    public function incrementAndEcho() {
        $this->attemptWrite();
        // or $this->attemptWriteWithMethod(__METHOD__);
        // or $this->attemptWriteWithMessage('What the exception will say if it's frozen');

        // now, your method's state-changing logic.
        echo ++$this->callcount;
    }

    public function justEcho() {
        echo $this->callcount;
    }
}

$counter = new Counter();
$counter->isFrozen(); // return FALSE
$counter->incrementAndEcho(); // prints '1'

$counter->freeze();
$counter->isFrozen(); // return TRUE

$counter->justEcho(); // prints '1'
$counter->incrementAndEcho(); // throws FrozenObjectException



use Frozone\Lockable;
use Frozone\LockableTrait;

class Counter implements Lockable {
    use LockableTrait;

    protected $callcount = 0;

    public function incrementAndEcho() {
        $this->attemptWrite();
        // or $this->attemptWriteWithMethod(__METHOD__);
        // or $this->attemptWriteWithMessage('What the exception will say if it's frozen');

        // now, your method's state-changing logic.
        echo ++$this->callcount;
    }

    public function justEcho() {
        echo $this->callcount;
    }
}

$counter = new Counter();
$counter->isLocked(); // return FALSE
$counter->incrementAndEcho(); // prints '1'

$key = mt_rand(1, 10000); // Use a key appropriate for your use case
$counter->lock($key);
$counter->isLocked(); // return TRUE

$counter->justEcho(); // prints '1'
$counter->incrementAndEcho(); // throws LockedObjectException
$counter->unlock('foo'); // throws LockedObjectException; wrong key
$counter->lock('foo'); // throws LockedObjectException; already locked

$counter->unlock($key);
$counter->isLocked(); // return FALSE
$counter->incrementAndEcho(); // prints '2'