Implementation of singleton design pattern in PHP5.4+ using a trait.
Install via Composer
$ composer require web6/singleton
Configure autoloading by including Composer's generated file :
include_once('vendor/autoload.php');
To create a singleton class simply use the W6\Sinfleton\SingletonTrait
and move the __construct()
logic to the init()
method.
class App {
use \W6\Singleton\SingletonTrait;
public $message = 'Not inited';
protected function init() {
$this->message = 'Inited';
}
}
Anywhere in your application you can request the same instance of the class.
$app = App::instance();
echo $app->message;