A minimal and testable singleton container for managing and retrieving shared instances in PHP.
composer require welbertymartins/php-singleton
use WelbertyMartins\Singleton\Singleton;
// Store a shared object in the global singleton container
Singleton::root()->remember(fn() => new MyService());
// Retrieve it later
$service = Singleton::root()->make(MyService::class);
Or use an isolated container:
$container = Singleton::local();
$container->remember(fn() => new MyService(), 'custom_service');
$service = $container->make('custom_service');
composer install
composer test
Includes PHPUnit tests, PSR-12 code style checking, and static analysis via Psalm.
src/ → Main singleton implementation
test/ → PHPUnit test suite
- 🧩 Global and isolated singleton instances
- 🛡️ Strict type safety
- ⚡ Lightweight, zero-dependency
- ✅ PSR-4 autoloading
- 🧪 Fully tested
Returns the globally shared singleton instance.
Returns a new isolated singleton instance.
Stores an object returned by a factory under a given name (or class name by default).
Retrieves a stored instance by name, or the last remembered instance.
This project is open-sourced under the MIT license.
Contributions, issues, and feature requests are welcome!
- Fork this repository
- Create a feature branch (
git checkout -b feature/your-feature
) - Submit a pull request 🚀