PHPackages                             blackbonjour/service-manager - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. blackbonjour/service-manager

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

blackbonjour/service-manager
============================

Small, lightweight and factory-biased service manager based on the PSR-11 standard.

1.6.0(11mo ago)1257[2 issues](https://github.com/BlackBonjour/service-manager/issues)[1 PRs](https://github.com/BlackBonjour/service-manager/pulls)MITPHPPHP ^8.3CI failing

Since Sep 18Pushed 11mo ago1 watchersCompare

[ Source](https://github.com/BlackBonjour/service-manager)[ Packagist](https://packagist.org/packages/blackbonjour/service-manager)[ Docs](https://github.com/BlackBonjour/service-manager)[ RSS](/packages/blackbonjour-service-manager/feed)WikiDiscussions master Synced today

READMEChangelog (8)Dependencies (5)Versions (9)Used By (0)

Service Manager
===============

[](#service-manager)

Small, lightweight and factory-biased service manager based on the PSR-11 standard.

[![Latest Stable Version](https://camo.githubusercontent.com/d24f094168c95d3adaab5ca31d0973735bb1872e3210535fef55f78d2db51f79/68747470733a2f2f706f7365722e707567782e6f72672f626c61636b626f6e6a6f75722f736572766963652d6d616e616765722f762f737461626c65)](https://packagist.org/packages/blackbonjour/service-manager)[![License](https://camo.githubusercontent.com/9684a86ce0153b8fef6152d9d024f066b2979315f6620f5b7785a159b83da492/68747470733a2f2f706f7365722e707567782e6f72672f626c61636b626f6e6a6f75722f736572766963652d6d616e616765722f6c6963656e7365)](https://packagist.org/packages/blackbonjour/service-manager)

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [Configuration](#configuration)
    - [Services](#services)
    - [Factories](#factories)
    - [Abstract Factories](#abstract-factories)
    - [Invokables](#invokables)
    - [Aliases](#aliases)
- [Advanced Usage](#advanced-usage)
    - [Creating Services with Options](#creating-services-with-options)
    - [Using Array Access](#using-array-access)
    - [Removing Services](#removing-services)
- [Abstract Factories](#abstract-factories-1)
    - [DynamicFactory](#dynamicfactory)
    - [ReflectionFactory](#reflectionfactory)
- [API Reference](#api-reference)
    - [ServiceManager](#servicemanager)
    - [FactoryInterface](#factoryinterface)
    - [AbstractFactoryInterface](#abstractfactoryinterface)
    - [InvokableFactory](#invokablefactory)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require blackbonjour/service-manager
```

Basic Usage
-----------

[](#basic-usage)

```
use BlackBonjour\ServiceManager\ServiceManager;

// Create a new service manager
$serviceManager = new ServiceManager();

// Add a service directly
$serviceManager->addService('config', [
    'db' => [
        'host' => 'localhost',
        'user' => 'root',
        'password' => 'secret',
    ],
]);

// Retrieve a service
$config = $serviceManager->get('config');
```

Configuration
-------------

[](#configuration)

The ServiceManager constructor accepts several configuration arrays:

```
$serviceManager = new ServiceManager(
    services: [],          // Pre-created service instances
    factories: [],         // Factories for creating services
    abstractFactories: [], // Abstract factories for dynamic service creation
    invokables: [],        // Classes that can be instantiated directly
    aliases: [],           // Alternative names for services
);
```

### Services

[](#services)

Services are pre-created instances that are stored in the container:

```
// Via constructor
$serviceManager = new ServiceManager([
    'config' => ['debug' => true],
    'logger' => new Logger(),
]);

// Via method
$serviceManager->addService('config', ['debug' => true]);
$serviceManager->addService('logger', new Logger());
```

### Factories

[](#factories)

Factories are responsible for creating service instances. They can be:

1. Classes implementing `FactoryInterface`
2. Callable objects
3. Class strings that resolve to one of the above

```
// Using a factory class
$serviceManager->addFactory(Database::class, DatabaseFactory::class);

// Using a callable
$serviceManager->addFactory('logger', function($container, $requestedName) {
    return new Logger();
});

// Via constructor
$serviceManager = new ServiceManager(
    factories: [
        Database::class => DatabaseFactory::class,
        'logger' => function($container, $requestedName) {
            return new Logger();
        },
    ]
);
```

### Abstract Factories

[](#abstract-factories)

Abstract factories are used when a service is not explicitly defined. They determine if they can create a requested service:

```
// Add an abstract factory
$serviceManager->addAbstractFactory(new DynamicFactory());

// Or via constructor
$serviceManager = new ServiceManager(
    abstractFactories: [
        new DynamicFactory(),
        ReflectionFactory::class,
    ]
);
```

### Invokables

[](#invokables)

Invokables are classes that can be instantiated directly without a factory:

```
// Add an invokable
$serviceManager->addInvokable(stdClass::class);

// Via constructor
$serviceManager = new ServiceManager(
    invokables: [
        stdClass::class,
        SomeClass::class,
    ]
);
```

### Aliases

[](#aliases)

Aliases provide alternative names for services:

```
// Add an alias
$serviceManager->addAlias('configuration', 'config');

// Via constructor
$serviceManager = new ServiceManager(
    aliases: [
        'configuration' => 'config',
        'db' => Database::class,
    ]
);
```

Advanced Usage
--------------

[](#advanced-usage)

### Creating Services with Options

[](#creating-services-with-options)

You can create services with additional options:

```
// Define a factory that accepts options
$serviceManager->addFactory('database', function($container, $requestedName, $options = null) {
    return new Database(
        $options['host'] ?? 'localhost',
        $options['user'] ?? 'root',
        $options['password'] ?? 'secret'
    );
});

// Create the service with options
$db = $serviceManager->createService('database', [
    'host' => 'db.example.com',
    'user' => 'admin',
    'password' => 'password123'
]);
```

### Using Array Access

[](#using-array-access)

The ServiceManager implements `ArrayAccess`, allowing you to use array syntax:

```
// Add a service
$serviceManager['config'] = ['debug' => true];

// Check if a service exists
if (isset($serviceManager['config'])) {
    // Service exists
}

// Get a service
$config = $serviceManager['config'];

// Remove a service
unset($serviceManager['config']);
```

### Removing Services

[](#removing-services)

You can remove services from the container:

```
$serviceManager->removeService('config');
// or
unset($serviceManager['config']);
```

Abstract Factories
------------------

[](#abstract-factories-1)

### DynamicFactory

[](#dynamicfactory)

The `DynamicFactory` looks for a factory class with the same name as the requested service plus "Factory":

```
// Add the DynamicFactory
$serviceManager->addAbstractFactory(new DynamicFactory());

// Now if you request MyService, it will look for MyServiceFactory
$service = $serviceManager->get(MyService::class);
```

### ReflectionFactory

[](#reflectionfactory)

The `ReflectionFactory` uses PHP's Reflection API to automatically instantiate classes and resolve their dependencies:

```
// Add the ReflectionFactory
$serviceManager->addAbstractFactory(new ReflectionFactory());

// Now you can get any class that has constructor dependencies registered in the container
$service = $serviceManager->get(MyService::class);
```

API Reference
-------------

[](#api-reference)

### ServiceManager

[](#servicemanager)

The main container class implementing PSR-11's `ContainerInterface`.

**Methods:**

- `__construct(array $services = [], array $factories = [], array $abstractFactories = [], array $invokables = [], array $aliases = [])`
- `addAbstractFactory(AbstractFactoryInterface|string $abstractFactory): void`
- `addAlias(string $alias, string $id): void`
- `addFactory(string $id, FactoryInterface|callable|string $factory): void`
- `addInvokable(string $id): void`
- `addService(string $id, mixed $service): void`
- `createService(string $id, ?array $options = null): mixed`
- `get(string $id): mixed`
- `has(string $id): bool`
- `removeService(string $id): void`

### FactoryInterface

[](#factoryinterface)

Interface for factories that create services.

**Methods:**

- `__invoke(ContainerInterface $container, string $service, ?array $options = null)`

### AbstractFactoryInterface

[](#abstractfactoryinterface)

Interface for abstract factories that can dynamically determine if they can create a service.

**Methods:**

- `canCreate(ContainerInterface $container, string $service): bool`
- `__invoke(ContainerInterface $container, string $service, ?array $options = null)` (inherited from FactoryInterface)

### InvokableFactory

[](#invokablefactory)

A factory for creating instances of classes without dependencies.

**Methods:**

- `__invoke(ContainerInterface $container, string $service, ?array $options = null)`

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance30

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~296 days

Recently: every ~348 days

Total

8

Last Release

352d ago

Major Versions

1.5.0 → 2.0.x-dev2025-05-16

PHP version history (3 changes)1.0.0PHP &gt;=7.3

1.4.0PHP ^8.1

1.5.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/204c2f409bdf9d8041584a0f0c10480070d49814385df66a8fa895f6e64ae7c8?d=identicon)[BlackBonjour](/maintainers/BlackBonjour)

---

Top Contributors

[![BlackBonjour](https://avatars.githubusercontent.com/u/13346461?v=4)](https://github.com/BlackBonjour "BlackBonjour (31 commits)")

---

Tags

containerPSR-11service-manager

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/blackbonjour-service-manager/health.svg)

```
[![Health](https://phpackages.com/badges/blackbonjour-service-manager/health.svg)](https://phpackages.com/packages/blackbonjour-service-manager)
```

###  Alternatives

[php-di/php-di

The dependency injection container for humans

2.8k48.9M994](/packages/php-di-php-di)[laminas/laminas-servicemanager

Factory-Driven Dependency Injection Container

15955.1M694](/packages/laminas-laminas-servicemanager)[slince/di

A flexible dependency injection container

20260.4k6](/packages/slince-di)[chubbyphp/chubbyphp-container

A simple PSR-11 container implementation.

1978.4k14](/packages/chubbyphp-chubbyphp-container)[phpwatch/simple-container

A fast and minimal PSR-11 compatible Dependency Injection Container with array-syntax and without auto-wiring

1810.1k2](/packages/phpwatch-simple-container)[selective/container

A simple PSR-11 container implementation with autowiring.

1220.4k4](/packages/selective-container)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
