Skip to content

Controllers & Container

Closures are fine for a handful of endpoints. As an API grows, group related request handling in controller classes. PAM HTTP builds controllers through its container, so constructors and action methods receive their dependencies automatically, and request-scoped services never leak into the next request.

A controller is a plain class. Register a method with an array handler:

src/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Http\Resources\UserResource;
use App\Services\UserService;
final readonly class UserController
{
public function __construct(private UserService $users) {}
public function show(int $id): UserResource
{
return new UserResource($this->users->find($id));
}
}
index.php
$app->get('/users/{id}', [UserController::class, 'show'])
->where('id', Pam\Api\RouteConstraint::Integer);

A class with __invoke() can be registered by name:

final readonly class CreateOrderController
{
public function __invoke(StoreOrderRequest $request, OrderService $orders): OrderResource
{
return new OrderResource($orders->create($request->dto(CreateOrderData::class)), 201);
}
}
$app->post('/orders', CreateOrderController::class);

The container builds a controller for every request that reaches it. Constructor parameters typed with a class are resolved recursively from the container; parameters with defaults use the default, and nullable parameters receive null when nothing else applies.

Action parameters are resolved in this order:

  1. Route parameters by name. {id} fills $id. A parameter typed with a class is converted through route model binding.
  2. The current request and response. Parameters typed Pam\Http\Request or Pam\Http\Response receive the objects of the current request.
  3. The container. Any other class, including form requests, scoped services and the authenticated Principal.
  4. Defaults, then null for nullable parameters. Anything else throws.
public function update(int $id, UpdateUserRequest $request, Response $response, AuditLog $audit): Response
{
// ...
}

$app->container() returns the application’s Pam\Api\Container\Container. It resolves any instantiable class without configuration, so you only register bindings for interfaces, factories and lifetimes.

src/Providers/AppServiceProvider.php
$container = $app->container();
$container->bind(UserRepository::class, ArcanoUserRepository::class);
$container->singleton(HttpClient::class, static fn () => new HttpClient(timeout: 5));
$container->scoped(CurrentUser::class);
$container->instance(Clock::class, new SystemClock());

The second argument of bind(), singleton() and scoped() can be omitted (build the class itself), a class name (resolve another entry) or a factory callable(Container): mixed.

Method Lifetime Use it for
bind() Transient: a new value on every resolution. Stateless services, repositories.
singleton() Singleton: one value for the worker’s lifetime. Clients, connection pools, configuration.
scoped() Scoped: one value per request, discarded when the request ends. Current user, unit of work, request context.
instance() A pre-built singleton. Values created during boot.
scopedInstance() A pre-built value for the current request only. Middleware that publishes request state.

Each request gets a fresh scope, and request Fibers never share one. Scoped values are discarded in a finally block, so they disappear even when the handler throws. Resolving a scoped entry outside a request throws a LogicException.

// In middleware: publish the request's tenant for everything downstream.
$container->scopedInstance(Tenant::class, $tenant);
// Later in the same request:
$tenant = $container->scopedValue(Tenant::class); // null when not set

$container->diagnostics() returns state (ContainerState::Idle = 1 or RequestActive = 2), scopedEntries, singletonEntries and bindings. Use it in tests to check that no request state survives a request.

Providers group registrations. They implement Pam\Contracts\Package\ServiceProviderInterface:

src/Providers/AppServiceProvider.php
namespace App\Providers;
use App\Repositories\ArcanoProductRepository;
use App\Repositories\ProductRepository;
use Pam\App;
use Pam\Contracts\Http\ApplicationInterface;
use Pam\Contracts\Package\ServiceProviderInterface;
final readonly class AppServiceProvider implements ServiceProviderInterface
{
public function register(ApplicationInterface $application): void
{
if ($application instanceof App) {
$application->container()->bind(ProductRepository::class, ArcanoProductRepository::class);
}
}
public function boot(ApplicationInterface $application): void
{
}
}
index.php
$app->provider(new AppServiceProvider());

register() runs immediately, while the application is still mutable: add bindings, routes and middleware there. boot() runs once, after every provider is registered, when the application freezes (on the first request, listen() or boot()).

Console scripts such as migration runners call $app->boot(). It boots the providers and freezes the configuration without dispatching a synthetic request, and it is safe to call more than once:

bin/migrate
$app = new App(discoverPackages: false);
$app->provider(new AppServiceProvider());
$app->boot();
$service = $app->container()->get(ReportService::class);

When discoverPackages is true (the default), new App() reads vendor/composer/installed.json from the current working directory and registers the providers that packages declare under extra.pam.providers:

composer.json (of a package)
{
"extra": {
"pam": {
"providers": ["Acme\\Billing\\BillingServiceProvider"]
}
}
}

The discovered list is cached in .pam/cache. Pass discoverPackages: false, or set PAM_DISABLE_PACKAGE_DISCOVERY=1, to keep the configuration fully explicit.