https://github.com/petrknap/php-singleton
Singleton pattern for PHP
https://github.com/petrknap/php-singleton
design-pattern php php-library singleton singleton-pattern
Last synced: 7 months ago
JSON representation
Singleton pattern for PHP
- Host: GitHub
- URL: https://github.com/petrknap/php-singleton
- Owner: petrknap
- License: lgpl-3.0
- Created: 2016-01-08T11:14:36.000Z (about 10 years ago)
- Default Branch: main
- Last Pushed: 2025-04-12T19:15:45.000Z (10 months ago)
- Last Synced: 2025-05-15T19:06:33.579Z (9 months ago)
- Topics: design-pattern, php, php-library, singleton, singleton-pattern
- Language: PHP
- Homepage:
- Size: 38.1 KB
- Stars: 4
- Watchers: 1
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: COPYING
- Authors: AUTHORS
Awesome Lists containing this project
README
# Singleton pattern for PHP
Simple implementation of singleton (anti-)pattern.
## Why use a singleton?
Because it can solve deadlocks and other problems. See this example:
```php
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...
```php
$first = new UnsafeFileAppender(); // OK
$second = new UnsafeFileAppender(); // Deadlock
```
...so simply convert it into singleton...
```php
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.
```php
$first = SafeFileAppender::getInstance(); // OK
$second = SafeFileAppender::getInstance(); // OK
```
---
Run `composer require petrknap/singleton` to install it.
You can [support this project via donation](https://petrknap.github.io/donate.html).
The project is licensed under [the terms of the `LGPL-3.0-or-later`](./COPYING.LESSER).