https://github.com/phpnomad/singleton
Trait-based singleton pattern implementation for PHPNomad
https://github.com/phpnomad/singleton
design-pattern framework php phpnomad platform-agnostic singleton
Last synced: 6 days ago
JSON representation
Trait-based singleton pattern implementation for PHPNomad
- Host: GitHub
- URL: https://github.com/phpnomad/singleton
- Owner: phpnomad
- License: mit
- Created: 2023-10-13T12:10:16.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2026-04-15T04:19:30.000Z (about 2 months ago)
- Last Synced: 2026-05-09T04:45:47.669Z (29 days ago)
- Topics: design-pattern, framework, php, phpnomad, platform-agnostic, singleton
- Language: PHP
- Homepage: https://phpnomad.com
- Size: 104 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# phpnomad/singleton
[](https://packagist.org/packages/phpnomad/singleton) [](https://packagist.org/packages/phpnomad/singleton) [](https://packagist.org/packages/phpnomad/singleton) [](https://packagist.org/packages/phpnomad/singleton)
`phpnomad/singleton` is a single-trait package for [PHPNomad](https://phpnomad.com). It provides `WithInstance`, a trait that gives any class a static `instance()` method returning a lazily-created, per-class singleton. It has zero runtime dependencies and is what `phpnomad/facade` and the rest of the framework use whenever a class needs a single shared instance without reaching for a container.
## Installation
```bash
composer require phpnomad/singleton
```
## Quick Start
Add the trait to a class, then call `instance()` to get the shared object.
```php
items[$key] = $value;
}
public function get(string $key)
{
return $this->items[$key] ?? null;
}
}
Registry::instance()->register('theme', 'dark');
$theme = Registry::instance()->get('theme'); // 'dark'
```
Every call to `Registry::instance()` returns the same object for the lifetime of the request.
## Overview
The package is intentionally tiny. The trait adds a protected static `$instance` property and a public static `instance()` method, and nothing else.
- Lazy initialization, so the instance is only built the first time `instance()` is called
- Late static binding (`new static`), so subclasses each get their own singleton rather than sharing the parent's
- Zero runtime dependencies, which means adding it to a project pulls in nothing else
- Lives under the `PHPNomad\Singleton\Traits` namespace, importable via `use PHPNomad\Singleton\Traits\WithInstance;`
- Used by `phpnomad/facade` to back its static service facades across the framework
## Documentation
The full package guide, including inheritance behavior, testing strategies, and when to reach for a DI container instead, lives at [phpnomad.com](https://phpnomad.com).
## License
MIT, see [LICENSE.txt](LICENSE.txt) for the full text.