PHP code example of petrknap / singleton

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

    

petrknap / singleton example snippets


class UnsafeFileAppender
{
    const MY_FILE = '/tmp/my.file';

    private $handle = null;

    public function __construct()
    {
        $this->handle = fopen(self::MY_FILE, 'a');
        flock($this->handle, LOCK_EX);
    }

    public function __destruct()
    {
        flock($this->handle, LOCK_UN);
        fclose($this->handle);
    }
}

$first = new UnsafeFileAppender();  // OK
$second = new UnsafeFileAppender(); // Deadlock

use PetrKnap\Singleton\SingletonInterface;
use PetrKnap\Singleton\SingletonTrait;

class SafeFileAppender extends UnsafeFileAppender implements SingletonInterface
{
    use SingletonTrait;

    private function __construct()
    {
        parent::__construct();
    }
}

$first = SafeFileAppender::getInstance();  // OK
$second = SafeFileAppender::getInstance(); // OK