petrknap / php-singleton
Singleton pattern for PHP
Fund package maintenance!
Other
Installs: 131 747
Dependents: 14
Suggesters: 0
Security: 0
Stars: 4
Watchers: 2
Forks: 2
Open Issues: 0
Requires
- php: >=8.1
- petrknap/shorts: ^2.1
Requires (Dev)
- nunomaduro/phpinsights: ^2.11
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-04-27 11:52:24 UTC
README
Simple implementation of singleton (anti-)pattern.
Why use a singleton?
Because it can solve deadlocks and other problems. See this example:
class UnsafeFileAppender { const MY_FILE = '/tmp/my.file'; private $handle = null; public function __construct() { $this->handle = fopen(self::MY_FILE, 'a'); flock($this->handle, LOCK_EX); } public function __destruct() { flock($this->handle, LOCK_UN); fclose($this->handle); } }
You cannot create two instances at the same time with this code...
$first = new UnsafeFileAppender(); // OK $second = new UnsafeFileAppender(); // Deadlock
...so simply convert it into singleton...
use PetrKnap\Singleton\SingletonInterface; use PetrKnap\Singleton\SingletonTrait; class SafeFileAppender extends UnsafeFileAppender implements SingletonInterface { use SingletonTrait; private function __construct() { parent::__construct(); } }
...and use the same instance twice.
$first = SafeFileAppender::getInstance(); // OK $second = SafeFileAppender::getInstance(); // OK
Run composer require petrknap/singleton
to install it.
You can support this project via donation.
The project is licensed under the terms of the LGPL-3.0-or-later
.