welbertymartins / php-singleton
Minimal and testable singleton container for object sharing and retrieval
v8.2.0
2025-06-29 02:41 UTC
Requires
- php: ^8.2
Requires (Dev)
- phpunit/phpunit: ^9.6
- squizlabs/php_codesniffer: ^3.7
- vimeo/psalm: ^5.10
This package is auto-updated.
Last update: 2025-06-29 03:04:29 UTC
README
A minimal and testable singleton container for managing and retrieving shared instances in PHP.
๐ฆ Installation
composer require welbertymartins/php-singleton
๐ Quick Start
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');
๐งช Running Tests
composer install
composer test
Includes PHPUnit tests, PSR-12 code style checking, and static analysis via Psalm.
๐ Project Structure
src/ โ Main singleton implementation
test/ โ PHPUnit test suite
โ Features
- ๐งฉ Global and isolated singleton instances
- ๐ก๏ธ Strict type safety
- โก Lightweight, zero-dependency
- โ PSR-4 autoloading
- ๐งช Fully tested
๐ API Overview
Singleton::root(): Singleton
Returns the globally shared singleton instance.
Singleton::local(): Singleton
Returns a new isolated singleton instance.
remember(callable $factory, string $name = '', bool $force = false): self
Stores an object returned by a factory under a given name (or class name by default).
make(string $name = ''): ?object
Retrieves a stored instance by name, or the last remembered instance.
๐ License
This project is open-sourced under the MIT license.
๐ค Contributing
Contributions, issues, and feature requests are welcome!
- Fork this repository
- Create a feature branch (
git checkout -b feature/your-feature
) - Submit a pull request ๐
๐ Useful Links
- ๐ฆ Packagist
---
Would you like me to create the `LICENSE`, `.gitignore`, `.gitattributes`, and `GitHub Actions` workflow file (`test.yml`) next?