Documentation menu

Reference

taphra/container

PSR-11 service container and ServiceProvider base class for Taphra.

It is a standalone package: it does not depend on the taphra/taphra framework and works in any PHP 8.2+ project.

Requirements

#
  • PHP >= 8.2
  • psr/container ^2.0

Installation

#
Shell
composer require taphra/container

Container

#

Taphra\Container\Container implements Psr\Container\ContainerInterface. Every binding is a singleton: the factory runs on the first get() and the result is reused after that, even when it is null.

PHP
use Taphra\Container\Container;

$c = new Container();

// Bind a factory (receives the container as its argument)
$c->bind('mailer', fn($c) => new Mailer($c->get('config')));
$c->bind(\Psr\Log\LoggerInterface::class, fn($c) => $c->get('logger'));

// Register a pre-resolved value
$c->instance('db', $existingConnection);

// Resolve
$mailer = $c->get('mailer');   // factory called once; result cached
$c->has('mailer');             // true

// Re-binding replaces the cached instance
$c->bind('mailer', fn($c) => new MockMailer());

// bind() and instance() return the container, so calls can be chained
$c->instance('config', ['dsn' => 'smtp://localhost'])
  ->bind('clock', fn() => new DateTimeImmutable());

Exceptions:

  • Taphra\Container\NotFoundException (implements Psr\Container\NotFoundExceptionInterface): no binding or instance exists for the ID.
  • Taphra\Container\ContainerException (implements Psr\Container\ContainerExceptionInterface): a factory threw; the original exception is available from getPrevious().

ServiceProvider

#

Taphra\ServiceProvider is an abstract base class for grouping the bindings of one feature.

PHP
use Taphra\Container\Container;
use Taphra\ServiceProvider;

class MailerServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Bind only here; do not call $this->app->get()
        $this->app->bind(Mailer::class, fn($c) => new Mailer($c->get('config')['dsn']));
    }

    public function boot(): void
    {
        // Safe to resolve here: every provider has run register()
        $this->app->get(Mailer::class)->setDefaultFrom('[email protected]');
    }
}

Providers run in two phases:

  1. register() on every provider: bind services, never resolve them.
  2. boot() on every provider, after all register() calls: resolving is safe. The default boot() does nothing.

$this->app is the Container passed to the constructor. Without the framework, run the phases yourself:

PHP
$c = new Container();
$c->instance('config', ['dsn' => 'smtp://localhost']);

$providers = [new MailerServiceProvider($c) /* , ... */];
foreach ($providers as $p) { $p->register(); }
foreach ($providers as $p) { $p->boot(); }

Used by Taphra Core

#

taphra/taphra depends on this package. The framework wires its own services in Taphra\Container\TaphraContainerFactory, which lives in the framework because it refers to framework classes (logger, router, HTTP layer).

In a Taphra app, Taphra\ProviderLoader finds the providers in app/Providers/ and those listed under app.providers in app/Config/app.yml, and runs both phases for you.

Package Layout

#
Text
packages/container/
  composer.json
  src/
    Container/
      Container.php          # PSR-11 container
      ContainerException.php # Psr\Container\ContainerExceptionInterface
      NotFoundException.php  # Psr\Container\NotFoundExceptionInterface
    ServiceProvider.php      # Abstract base (namespace Taphra\)