PHP code example of cse / base-singleton

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

    

cse / base-singleton example snippets


class ExampleSingleton
{
    use SingletonTrait;
    ...
}
$instance = ExampleSingleton::getInstance();
$instanceName = ExampleSingleton::getInstance('instance_name');

class ModelSingleton
{
    use SingletonTrait;

    protected $param = 0;

    /**
     * @param int $param
     */
    public function setParam(int $param): void
    {
        $this->param = $param;
    }

    /**
     * @return int
     */
    public function getParam(): int
    {
        return $this->param;
    }
}

$instance = ModelSingleton::getInstance();
$instance->setParam(10);
$instance->getParam();
// 10

$instance2 = ModelSingleton::getInstance('new');
$instance2->setParam(20);
$instance->getParam();
// 10
$instance2->getParam();
// 20

$instance3 = ModelSingleton::getInstance();
$instance3->setParam(30);
$instance->getParam();
// 30
$instance2->getParam();
// 20
$instance3->getParam();
// 30

try {
    $clone = clone ModelSingleton::getInstance();
} catch (CSESingletonException $e) {
    // Singleton can not using clone
}

try {
    $serialize = serialize(ModelSingleton::getInstance());
} catch (CSESingletonException $e) {
    // Singleton can not serialize
}

try {
    ...
} catch (CSESingletonException $e) {
    // Singleton can not deserialize
}
bash
phpunit PATH/TO/PROJECT/tests/
bash
phpunit --configuration PATH/TO/PROJECT/phpunit.xml