2.5. Definition Providers

You can create one or more Provider classes to work with a Definitions instance. To do so, implement the Provider interface ...

use Capsule\Di\Definitions;
use Capsule\Di\Provider;

class PdoProvider implements Provider
{
    public function provide(Definitions $def) : void
    {
        $def->{PDO::CLASS}
            ->arguments([
                $def->env('PDO_DSN'),
                $def->env('PDO_USERNAME'),
                $def->env('PDO_PASSWORD')
            ]);
    }
}

... then pass an iterable of Provider instances to a new Container:

$providers = [
    new PdoProvider(),
];

$container = new Container(
    new Definitions(),
    $providers
);

The $providers may be any iterable of Provider instances, not just an array.

You can use Provider instances for definitions organized by:

  • classes or class collections
  • libraries or library collections
  • packages or package collections
  • HTTP or command line interfaces
  • Development, test, or production environments

It is up to you how you organize your Provider instances. For example, you may organize them by DDD and environment layers, like so:

$providers = [
    new DomainLayerProvider(),
    new ApplicatonLayerProvider(),
    new InfrastructureLayerProvider(),
    new HttpLayerProvider(),
    new ProductionEnvironmentProvider(),
];

You may wish to make your Provider instances mixable in various combinations, so you can reuse "lower" or "inner" definitions in concert with "higher" or "outer" definitions. For example, reusing some core definitions in a different environment:

$providers = [
    new DomainLayerProvider(),
    new ApplicatonLayerProvider(),
    new IntegrationTestingProvider(),
];