Overview

Description

Caldera Container is a PSR-11 implementation.

As with the other Caldera components it has been built to be swappable and modular, which means you can change it for any other PSR-11 implementation should you like to.

Installation

The easisest way to install it is to use Composer:

composer require vecode/caldera-container

Requires

  • php: >=8.1
  • ext-mbstring: *
  • psr/container: ^2.0

Basic usage

Getting started

Using it is pretty simple, to register a service use the add method:

use Caldera\Container\Container;
use Contoso\Generator;

$container = new Container();
$container->add(Generator::class);

You may also register a service as shared by passing a second argument:

use Contoso\Generator;

$container->add(Generator::class, true);

If you are registering an implementation of an interface, pass the implementation class name as a third parameter:

use Contoso\AdapterInterface;
use Contoso\FileAdapter;

$container->add(AdapterInterface::class, true, FileAdapter::class);

Concrete objects are also supported in both cases:

use Contoso\Generator;

$container->add(Generator::class, true, $generator); // $generator is an existing instance of Generator
use Contoso\AdapterInterface;
use Contoso\FileAdapter;

$container->add(AdapterInterface::class, true, $adapter); // $adapter is an existing instance of FileAdapter

And of course, factory functions are also supported:

use Contoso\Generator;

$container->add(Generator::class, true, function($container) {
    $generator = new Generator();
    return $generator;
});
use Contoso\AdapterInterface;
use Contoso\FileAdapter;

$container->add(AdapterInterface::class, true, function($container) {
    $adapter = new FileAdapter( dirname(__FILE__) );
    return $adapter;
});

To obtain an instance use the get method:

use Contoso\Generator;

$generator = $container->get(Generator::class);

Or using array notation:

use Contoso\Generator;

$generator = $container[Generator::class];

According to the PSR-11 specification you may also check if a service is present in the container with the has method:

use Contoso\Generator;

if ( $container->has(Generator::class) ) {
    // Do something
}

While checking for a service is not required by the specification, trying to get an unknown service out of the container will result in a NotFoundException thrown.

To remove a service use the remove method:

use Contoso\Generator;

$container->remove(Generator::class);
Autowiring

The implementation supports autowiring on the constructor parameters for dependency-injection.