okapi/singleton

PHP Singleton 是一个 PHP 库,允许您使用 trait 创建单例类。

1.0.3 2023-03-09 10:04 UTC

This package is auto-updated.

Last update: 2024-09-05 22:02:13 UTC


README

PHP Singleton

License: MIT Twitter: @WalterWoshid PHP: >=8.0 Packagist Build

Coverage - PHP 8.0 Coverage - PHP 8.1 Coverage - PHP 8.2

PHP Singleton 是一个 PHP 库,允许您使用 trait 创建单例类。

安装

composer require okapi/singleton

使用

<?php

use Okapi\Singleton\Singleton;

class GovernmentOfUSA
{
    // Add the singleton trait
    use Singleton;
    
    /**
     * Function to register the singleton. 
     * 
     * This function and the "initialized" methods are completely optional.
     * 
     * Can be static or non-static. 
     */
    public static function register(): void
    {
        // Get instance
        $instance = self::getInstance();
        
        // For non-static just use $this
        
        // Make sure the instance is only registered once
        $instance->ensureNotInitialized();
        
        // Do something
        // ...
        
        // Mark the instance as initialized
        $instance->setInitialized();
    }
    
    /**
     * Custom function
     */
    public function takeOverTheWorld(): void
    {
        // Make sure the instance is initialized
        $this->ensureInitialized();
        
        // Do something
        // ...
    }
}

// Other file

// Register the singleton
GovernmentOfUSA::register();

// Take over the world
$instance = GovernmentOfUSA::getInstance();
$instance->takeOverTheWorld();
// or
GovernmentOfUSA::getInstance()->takeOverTheWorld();

测试

  • 运行 composer run-script test
  • 运行 composer run-script test-coverage

表达您的支持

如果这个项目对您有帮助,请给一个 ⭐!

📝 许可证

版权所有 © 2023 Valentin Wotschel.
本项目遵循 MIT 许可证。