Multiton
A trait to implement the Multiton design pattern without any dependencies.
Installation
$ composer require michaelspiss/multiton
Basic Usage
One line is enough to turn a class (called DatabaseAccess only for demonstration purposes) into a multiton:
<?php
class DatabaseAccess {
use MichaelSpiss\DesignPatterns\Multiton;
...
}
To retrieve the multiton instance, simply call ::getInstance() with a unique identifier:
$instance = DatabaseAccess::getInstance('ID');
Another instance can be retrieved by doing the exact same with another ID.
During initialization the constructor is called with the identifier as argument.
You can change the __construct() method as you wish, as long as it only requires
the identifier as attribute and it's visibility is protected
, to prevent
instantiations via the new
operator.
PHP Requirements
- PHP >= 5.4
License
MIT