PHP abstract singleton patter.
composer require hametuha/singleton-pattern
Inherit from abstract class Hametuha\SingletonPattern\Singleton
.
<?php
use Hametuha\SingletonPattern\Singleton;
class SampleSingleton extends Singleton {
private $version = '';
/**
* This method is called inside constructor.
*/
protected function init() {
$this->version = get_wp_version();
}
/**
* Greeting.
*/
public function greet() {
echo 'Hello World!';
}
}
Then, call it outside.
<?php
SampleSingleton::get_instance()->greet();
// -> Hello World!
If you have PSR-0(or maybe PSR-4) based structure, you can bulk register them. For examle...
src
└Vendor
└Library
└NameSpace
├SampleClass
├OtherClass
└AnotherClass
You can call BulkRegister::enable
to load them all!
Hametuha\SingletonPatter\BulkRegister::enable( 'Vendor\Library\NameSpace', __DIR__ . '/src/Vendor/Library/NameSpace' );
// => 3(enabled class count)
Syntax is like below:
BulkRegister::enable( $namespace, $directory_to_scan, $subclass, $method )
$namespace
Name space prefix. In the case above,Vendor/Library\NameSpace
.$directory_to_scan
This directory will be scanned. Not recursively$subclasss
Class should be subclass of this class name. Defautl isHametuha\SingletonPattern\Singleton
.$method
Static method to call. Default isget_instance()
.
GPL 3.0 or later.