PHPackages                             nimbly/carton - 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. nimbly/carton

ActiveLibrary

nimbly/carton
=============

A simple PSR-11 container implementation offering reflection based autowiring.

2.2(1y ago)37.7k↑35.7%1MITPHPPHP ^8.2CI passing

Since Sep 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/nimbly/Carton)[ Packagist](https://packagist.org/packages/nimbly/carton)[ RSS](/packages/nimbly-carton/feed)WikiDiscussions master Synced today

READMEChangelog (8)Dependencies (5)Versions (11)Used By (1)

Carton
======

[](#carton)

[![Latest Stable Version](https://camo.githubusercontent.com/a545f957d1e4002afbfb9d2681386e938d69ca5380257a197a01a3ae22a10a33/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e696d626c792f636172746f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nimbly/carton)[![GitHub Workflow Status](https://camo.githubusercontent.com/ee6b0d6e1139f3d6f264fa614737099fa79f2b0d1eccc230810090f1d5691054/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6e696d626c792f636172746f6e2f636f7665726167652e796d6c3f7374796c653d666c61742d737175617265)](https://github.com/nimbly/Carton/actions/workflows/coverage.yml)[![Codecov branch](https://camo.githubusercontent.com/67f5c49b0024e2ee574030ec018aa8e5d0391fcc1c2c7f1e8b5d40aee7aea8ef/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6e696d626c792f636172746f6e2f6d61737465723f7374796c653d666c61742d737175617265)](https://app.codecov.io/github/nimbly/Carton)[![License](https://camo.githubusercontent.com/51b3beb31475136f1cdc89a259ca05c175ea8f22a3bea8b75b30cab871c1253e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6e696d626c792f636172746f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nimbly/carton)

A simple PSR-11 container implementation.

Requirements
------------

[](#requirements)

- PHP 8.2+

Features
--------

[](#features)

- PSR-11 compliant
- Singleton and factory builders
- Service providers
- Nested container support
- Reflection based autowiring
- Aliasing

Install
-------

[](#install)

```
composer require nimbly/carton
```

Getting the container
---------------------

[](#getting-the-container)

### Instantiate container

[](#instantiate-container)

You can create a new instance of a Container.

```
$container = new Container;
```

### Singleton instance

[](#singleton-instance)

Or use the container singleton `getInstance` method.

```
$container = Container::getInstance();
```

Basic usage
-----------

[](#basic-usage)

### Set an instance

[](#set-an-instance)

The most basic usage is to just assign an instance to the container itself.

```
$container->set(SomeInterface::class, new SomeClass);
```

Of course, you don't *need* to assign objects - it can be anything you like.

```
$container->set("timezone", "UTC");
$container->set("foo_fh", \fopen("/tmp/foo", "r"));
```

### Retrieving a value

[](#retrieving-a-value)

Grab a value from the container by its key.

```
$someClass = $container->get(SomeClass::class);
```

NOTE: Retrieving a value that does not exist will throw a `Nimbly\Carton\NotFoundException`.

### Checking for instance

[](#checking-for-instance)

You can check for the existance of items registered in the container.

```
if( $container->has(SomeClass::class) ){
	echo "Container has SomeClass::class.";
}
```

Advanced usage
--------------

[](#advanced-usage)

### Singleton builder

[](#singleton-builder)

The singleton builder will ensure only a single instance is ever returned when it is retrieved from the container. The singleton builder requires a `callable` that will be invoked when it needs to build your dependency and will pass along the `Container` instance as a single parameter.

It also has the added benefit over the `set` method by lazily calling your callback. I.e. it will only be created when it is actually needed.

```
$container->singleton(
	SomeClass::class,
	function(Container $container): void {
		return new SomeClass(
			$container->get("SomeDependency")
		);
	}
);
```

### Factory builder

[](#factory-builder)

The factory builder will create new instances each time it is retrieved from the container. The factory builder requires a `callable` that will be invoked when it needs to build your dependency and will pass along the `Container` instance as a single parameter.

Just like the singleton builder, it has the added benefit over the set method by lazily calling your callback. I.e. it will only be created when it is actually needed.

```
$container->factory(
	SomeClass::class,
	function(Container $container): SomeClass {
		return new SomeClass(
			$container->get("SomeDependency")
		);
	}
);
```

### Aliases

[](#aliases)

You can create aliases of your container items. These aliases simply point to an existing container item and fetch that item for you.

```
$container->set(Bar::class, new Bar);
$container->alias(Foo:class, Bar::class);
$instance = $container->get(Foo::class); // Returns Bar::class instance.
```

Alternatively, you can provide an alias or an array of aliases when calling `set`, `singleton`, or `factory`.

```
$container->singleton(
	Bar:class,
	function(Container $container): Bar {
		return new Bar;
	},
	[Foo::class, Baz::class]
)

$instance = $container->get(Bar::class); // Returns Bar::class instance.
$instance = $container->get(Foo::class); // Returns Bar::class instance.
$instance = $container->get(Baz::class); // Returns Bar::class instance.
```

### Autowiring

[](#autowiring)

You can have instances made for you automatically using the `make` method - which will attempt to pull dependencies in from the container itself or recursively attempt to `make` them if not found.

```
class Foo
{
	public function __construct(
        protected DateTime $date)
	{
	}
}

class Bar
{
	public function __construct(
        protected Foo $foo)
	{
	}
}

$bar = $container->make(Bar::class);
```

### Dependecy injection on instance methods

[](#dependecy-injection-on-instance-methods)

Calling an instance method couldn't be easier - Carton will attempt to autoresolve dependencies (autowire) for you when making a call to an instance method.

```
class BooksController
{
	public function get(ServerRequestInterface $request, string $isbn): Response
	{
		return new Response(
			Books::find($isbn)
		);
	}
}

$container->set(ServerRequestInterface::class, $serverRequest);
$response = $container->call([BooksController::class, "get"], ["isbn" => "123123"]);
```

### Adding additional containers

[](#adding-additional-containers)

You can extend Carton with additional PSR-11 compliant container instances by calling the `addContainer` method. When Carton attempts to resolve an item, it will always attempt to resolve locally first, and if not found, will loop through any additional containers you have provided.

For example, if you had a configuration manager that implemented `ContainerInterface` (PSR-11), you could add it to Carton.

```
$container->addContainer(
	new Config([
		new FileLoader(__DIR__ . "/config")
	])
);

$container->get("database.connections");
```

Now you can retrieve your configuration data through the container instance.

### Service providers

[](#service-providers)

Service providers allow you to organize your application dependencies in a set of classes.

Create service classes that implement `ServiceProviderInterface`.

```
class MyServiceProvider implements ServiceProviderInterface
{
	public function register(Container $container): void
	{
		$container->singleton(
			MyService::class,
			function(Container $container): void {
				return new MyService(
					$container->get(SomeDependency::class)
				);
			}
		);
	}
}
```

Then register your service providers with the container.

```
$container->register(new MyServiceProvider);
```

You can also register multiple services at once and register services by their class name.

```
// Register group of services at once.
$container->register([
	new MyServiceProvider,
	new MyOtherServiceProvider
]);

// Register services by class name.
$container->register(MyServiceProvider::class);

// Register group of services by class name.
$container->register([
	MyServiceProvider::class,
	MyOtherServiceProvider::class
]);
```

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance48

Moderate activity, may be stable

Popularity26

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity76

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 ~222 days

Recently: every ~378 days

Total

10

Last Release

387d ago

Major Versions

0.2 → 1.02019-12-29

1.2.1 → 2.02023-08-05

PHP version history (5 changes)0.1PHP &gt;= 7.2

1.2PHP ^7.4|^8.0

1.2.1PHP ^7.3|^8.0

2.0PHP ^8.0

2.2PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/2fdbed9ace23122d2f6af85ec0ddb4628d499893500f0d1c67742ca3aa33b05d?d=identicon)[brentscheffler](/maintainers/brentscheffler)

---

Top Contributors

[![brentscheffler](https://avatars.githubusercontent.com/u/723164?v=4)](https://github.com/brentscheffler "brentscheffler (47 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nimbly-carton/health.svg)

```
[![Health](https://phpackages.com/badges/nimbly-carton/health.svg)](https://phpackages.com/packages/nimbly-carton)
```

###  Alternatives

[akrabat/ip-address-middleware

PSR-15 middleware that determines the client IP address and stores it as a ServerRequest attribute

1702.4M15](/packages/akrabat-ip-address-middleware)[internal/dload

Downloads binaries.

97124.8k6](/packages/internal-dload)[nimbly/syndicate

A powerful queue and pubsub message publisher and consumer framework.

304.2k](/packages/nimbly-syndicate)[nimbly/limber

A super minimal HTTP framework that doesn't get in your way.

208.9k](/packages/nimbly-limber)

PHPackages © 2026

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