Documentation menu

Architecture

Service container and providers

Taphra ships a small PSR-11 container, Taphra\Container\Container, and a two-phase ServiceProvider base class for wiring your own services. This page covers both inside an application. The container works without the framework too: see packages/container/README.md.

The container is deliberately plain. It does not autowire: every service is registered with a factory you write. Controllers are created with new, without constructor injection; code that needs a service asks the container for it.

Contents

#

The container

#

bind() registers a factory. The factory receives the container and runs on the first get(); the result is kept and returned by every later get(), so every binding is a singleton. instance() registers a value that is already built.

PHP
use Taphra\Container\Container;
use Taphra\Container\ContainerException;
use Taphra\Container\NotFoundException;

$c = new Container();

$c->instance('settings', ['timezone' => 'Europe/Paris'])
  ->bind('zone', fn(Container $c) => new DateTimeZone($c->get('settings')['timezone']));

$a = $c->get('zone');
$b = $c->get('zone');
var_dump($a === $b);           // bool(true): the factory ran once
var_dump($c->has('settings')); // bool(true)

// Binding the same id again replaces the factory and drops the cached instance.
$c->bind('zone', fn() => new DateTimeZone('UTC'));
echo $c->get('zone')->getName(), "\n"; // UTC

try {
    $c->get('mailer');
} catch (NotFoundException $e) {
    echo $e->getMessage(), "\n"; // No binding registered for: mailer
}

// A factory that throws is reported as a ContainerException; the original
// exception is its previous one.
$c->bind('broken', fn() => throw new RuntimeException('no SMTP host'));
try {
    $c->get('broken');
} catch (ContainerException $e) {
    echo $e->getPrevious()->getMessage(), "\n"; // no SMTP host
}

NotFoundException and ContainerException implement the PSR-11 exception interfaces, so code typed against Psr\Container\ContainerInterface works with this container.

The application container

#

getContainer() returns the application's container. It is created on the first call, with these entries already bound, and that first call also runs your service providers:

Id Value
logger, Psr\Log\LoggerInterface a PSR-3 logger writing to app/tmp/Log/app.log (see Logging)
cache the framework cache, Taphra\Cache\Cache::getInstance()
router the router, Taphra\Router::getInstance()
config the class name Taphra\Config, for static calls such as Config::get()
request a PSR-7 ServerRequestInterface built from the PHP globals
pipeline a MiddlewarePipeline with JsonBodyMiddleware and ActionDispatcherMiddleware
PHP
use Psr\Log\LoggerInterface;

$logger = getContainer()->get(LoggerInterface::class);
$logger->info('Container ready');

var_dump(getContainer() === getContainer()); // bool(true): one container per process

The framework builds the container and boots the providers once per process: at the start of the first web request, on the default entry and on a PSR-15 pipeline alike (before routing, so a provider can add routes, see Routes from a package), and when php taphra starts (which then lists the commands each provider returns from commands()).

Service providers

#

A provider groups the bindings of one feature. Create one with:

Shell
php taphra make:provider Clock

This writes app/Providers/ClockServiceProvider.php. Here is a filled-in version, with the service it registers:

app/Services/Clock.php
<?php
// app/Services/Clock.php
namespace App\Services;

interface Clock
{
    public function now(): \DateTimeImmutable;
}
app/Services/SystemClock.php
<?php
// app/Services/SystemClock.php
namespace App\Services;

final class SystemClock implements Clock
{
    public function __construct(private \DateTimeZone $zone) {}

    public function now(): \DateTimeImmutable
    {
        return new \DateTimeImmutable('now', $this->zone);
    }
}
app/Providers/ClockServiceProvider.php
<?php
// app/Providers/ClockServiceProvider.php
namespace App\Providers;

use App\Services\Clock;
use App\Services\SystemClock;
use Psr\Log\LoggerInterface;
use Taphra\ServiceProvider;

class ClockServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Bind only: other providers may not have registered yet.
        $this->app->bind(Clock::class, fn() => new SystemClock(new \DateTimeZone('UTC')));
    }

    public function boot(): void
    {
        // Every provider has run register(), so resolving is safe here.
        $this->app->get(LoggerInterface::class)->debug('Clock bound');
    }
}

Providers run in two phases:

  1. register() on every provider. Bind services here; do not call $this->app->get(), because a service you depend on may belong to a provider that has not registered yet.
  2. boot() on every provider, once all of them have registered. Resolving services, subscribing event listeners and similar set-up go here. The default boot() does nothing.

$this->app is the application container.

Where providers are listed

#

The loader collects providers from two places, in this order:

  1. The providers list in app/Config/app.yml, for providers that live outside app/Providers/ (a package's provider, for example).
  2. Every *.php file in app/Providers/, in alphabetical order. The class name is the file name in the App\Providers namespace.

A class found in both places runs once. A listed name that is not a Taphra\ServiceProvider subclass is skipped.

YAML
# app/Config/app.yml
all:
  providers:
    - Taphra\Billing\BillingServiceProvider
PHP
use App\Services\Clock;

$clock = getContainer()->get(Clock::class);
echo $clock->now()->getTimezone()->getName(), "\n"; // UTC

Using services in controllers

#

A controller has no constructor injection: read what it needs from the container in the action.

app/Controllers/StatusController.php
<?php
// app/Controllers/StatusController.php
namespace App\Controllers;

use App\Services\Clock;
use Taphra\RestController;

class StatusController extends RestController
{
    public function index(): string
    {
        $clock = getContainer()->get(Clock::class);

        return $this->json(['time' => $clock->now()->format(DATE_ATOM)]);
    }
}

GET /status now answers {"time":"..."}. For a service you use in many actions, a protected helper on your base controller keeps the lookups in one place:

PHP
// app/Controllers/AppController.class.php (excerpt)
protected function clock(): \App\Services\Clock
{
    return getContainer()->get(\App\Services\Clock::class);
}

Command and query buses

#

Taphra\Bus\CommandBus sends a command object to its handler and returns what the handler returns; Taphra\Bus\QueryBus does the same for read-only queries with query(). Given a container, a bus builds a handler class from the container when the container has an entry for that class, and with new otherwise. That is how a handler gets its dependencies.

PHP
namespace App\Commands;

use App\Services\Clock;
use Taphra\Bus\CommandBus;

final class StampInvoice
{
    public function __construct(public readonly int $invoiceId) {}
}

final class StampInvoiceHandler
{
    public function __construct(private Clock $clock) {}

    public function handle(StampInvoice $command): string
    {
        return "invoice {$command->invoiceId} stamped at " . $this->clock->now()->format('Y-m-d');
    }
}

getContainer()->bind(StampInvoiceHandler::class, fn($c) => new StampInvoiceHandler($c->get(Clock::class)));

$bus = new CommandBus(getContainer());
$bus->register(StampInvoice::class, StampInvoiceHandler::class);

echo $bus->dispatch(new StampInvoice(42)), "\n";

php taphra make:command and php taphra make:handler (with --query for a query handler) scaffold the two classes. Without register(), a bus finds a handler by name only after setHandlerNamespace(): StampInvoiceCommand maps to StampInvoiceHandler in the namespace you give. addMiddleware(fn(object $command, callable $next) => ...) wraps every dispatch, for logging or a database transaction.

Swapping services in tests

#

instance() and bind() replace an entry and its cached value, so a test can put a fake in place before the code under test asks for it:

PHP
use App\Services\Clock;

getContainer()->instance(Clock::class, new class implements Clock {
    public function now(): \DateTimeImmutable
    {
        return new \DateTimeImmutable('2026-01-01 09:00:00', new \DateTimeZone('UTC'));
    }
});

echo getContainer()->get(Clock::class)->now()->format('Y-m-d H:i'), "\n"; // 2026-01-01 09:00

Providers run once per process. Taphra\ProviderLoader::reset() lets them run again, which is only useful when a test builds a new container itself.

Long-running workers

#

In FrankenPHP worker mode one PHP process serves many requests, and the container lives as long as the process: providers run once, and every service stays built between requests. Keep per-request data (the current user, the request) out of services. The request entry in particular is built once per container, so in worker mode it keeps the first request; read input through Taphra\Request, which is reset for every request, instead. See Deployment for what the worker resets between requests.