Skip to content

Basic Container usage

As described in the Getting started guide, there are several ways to construct a container instance. It does not matter whether the container is generated by the factory, custom built, or created dynamically — the runtime API is identical for all of them.

This page is a short overview of how you get a container and where the detailed API lives:

  • Parameters — reading, writing and checking configuration values.
  • Services — resolving, listing, injecting and removing services, plus metadata lookups.
  • Service Binding — registering new services at runtime.

Construction and parameters

The container constructor always accepts an initial array of parameters:

php
use ClanCats\Container\Container;

$container = new Container(['env' => 'production']);

The same initial parameters can be passed when you build a container through the factory:

php
$factory = new \ClanCats\Container\ContainerFactory(__DIR__ . '/cache');
$container = $factory->create('AppContainer', function($builder) {}, ['env' => 'production']);

These initial values are merged with any parameters already defined (for example the ones baked into a compiled container). See Parameters for the full reading and writing API.

The reserved container service

The name container is the only reserved service name and always refers to the container itself:

php
$container->get('container'); // === $container

Getting services and binding at runtime

Resolving services (get, has, available, isResolved, set, release, remove) is covered in Services. Registering new services on a live container — with a factory, a class name, or a closure — is covered in Service Binding. You can freely mix dynamically bound services with compiled ones.