welbertymartins/php-singleton

Minimal and testable singleton container for object sharing and retrieval

v8.2.0 2025-06-29 02:41 UTC

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!

  1. Fork this repository
  2. Create a feature branch (git checkout -b feature/your-feature)
  3. Submit a pull request ๐Ÿš€

๐Ÿ”— Useful Links


---

Would you like me to create the `LICENSE`, `.gitignore`, `.gitattributes`, and `GitHub Actions` workflow file (`test.yml`) next?