Kotchasan Framework Documentation

Kotchasan Framework Documentation

Singleton implementation

EN 05 Feb 2026 06:23

Singleton implementation

Kotchasan\Singleton is an Abstract Class implementing the Singleton Pattern, ensuring that a class has only one instance throughout the application lifecycle.

Usage

Extend the Kotchasan\Singleton class and implement the init method.

use Kotchasan\Singleton;

class MyConfig extends Singleton
{
    private $settings;

    /**
     * Initialization method (Called only once)
     */
    protected function init()
    {
        $this->settings = [
            'color' => 'red',
            'size' => 10
        ];
    }

    public function get($key)
    {
        return $this->settings[$key] ?? null;
    }
}

Instantiation

Use the getInstance() method to retrieve the instance.

// First call (Creates instance + calls init)
$config = MyConfig::getInstance();
echo $config->get('color'); // "red"

// Subsequent calls (Returns the same instance)
$config2 = MyConfig::getInstance();

Methods

getInstance(): static

Returns the instance of the class (creates it if it doesn't exist).

  • Returns: Class Instance

init()

Abstract method called upon first instantiation. Used for initialization logic.

  • Visibility: protected abstract (Must be implemented in subclass)

Important Notes

  1. Private Constructor: You cannot use new MyClass(). You must use MyClass::getInstance().
  2. Abstract: Kotchasan\Singleton cannot be used directly; it must be extended.