Controllers
Closures in routes.php are fine for a handful of endpoints. As an API grows, move the handling logic into controller classes: a ProductController can hold every action that deals with products, receive its dependencies through the constructor, and be tested on its own.
Nimbus creates a fresh controller instance for every request, so a controller can never carry state from one request into the next.
Writing Controllers
Section titled “Writing Controllers”Basic Controllers
Section titled “Basic Controllers”Generate a controller with the PAM CLI. It lands in app/Controllers:
pam make:controller ProductController<?php
declare(strict_types=1);
namespace App\Controllers;
use Pam\Http\Request;use Pam\Http\Response;
final readonly class ProductController{ public function index(Request $request, Response $response): Response { return $response->json(['data' => []]); }}Point a route at a controller method with a [Class::class, 'method'] pair:
use App\Controllers\ProductController;
$router->get('api/products', [ProductController::class, 'index']);Action methods must be public and concrete. Like closures, they can return a Response, an array, a string, or a Responsable such as a resource.
Single Action Controllers
Section titled “Single Action Controllers”A controller that does one thing can implement __invoke(). Register it by class name:
<?php
declare(strict_types=1);
namespace App\Controllers;
final readonly class ShowDashboard{ /** @return array<string, string> */ public function __invoke(): array { return ['page' => 'dashboard']; }}use App\Controllers\ShowDashboard;
$router->get('/dashboard', ShowDashboard::class);Controller Routes
Section titled “Controller Routes”When several routes use the same controller, the controller() group lets each route name only its method:
use App\Controllers\ProductController;use Nimbus\RouteRegistrar;
$router->controller(ProductController::class, function (RouteRegistrar $router): void { $router->get('api/products', 'index'); $router->post('api/products', 'store'); $router->get('api/products/{id}', 'show');});Resource Controllers
Section titled “Resource Controllers”A resource controller handles the create, read, update and delete actions of one kind of record. resource() maps the conventional routes to the conventional method names:
$router->resource('api/products', ProductController::class);| Method | Path | Action |
|---|---|---|
GET |
/api/products |
index |
POST |
/api/products |
store |
GET |
/api/products/{product} |
show |
PUT / PATCH |
/api/products/{product} |
update |
DELETE |
/api/products/{product} |
destroy |
A complete resource controller, with a repository injected through the constructor:
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Requests\StoreProductRequest;use App\Resources\ProductResource;use App\Services\ProductRepository;use Nimbus\Http\HttpException;use Nimbus\Http\ProblemCode;use Nimbus\Http\ResourceCollection;use Pam\Http\Response;
final readonly class ProductController{ public function __construct(private ProductRepository $products) { }
public function index(): ResourceCollection { return ProductResource::collection($this->products->all()); }
public function store(StoreProductRequest $request): ProductResource { $product = $this->products->create($request->validated());
return new ProductResource($product, 201); }
public function show(string $product): ProductResource { return new ProductResource($this->find($product)); }
public function update(string $product, StoreProductRequest $request): ProductResource { return new ProductResource($this->products->update($this->find($product), $request->validated())); }
public function destroy(string $product, Response $response): Response { $this->products->delete($this->find($product));
return $response->status(204)->send(null); }
/** @return array{id: int, name: string, price: int} */ private function find(string $id): array { return $this->products->find((int) $id) ?? throw new HttpException(404, ProblemCode::NotFound, 'Product not found.'); }}The parameter name of each route ({product}) is the singular of the last path segment, so the action receives it as $product. Add extra routes to the same controller with a closure:
$router->resource('api/products', ProductController::class, function (RouteRegistrar $products): void { $products->post('{product}/publish', 'publish'); // POST /api/products/{product}/publish});Dependency Injection
Section titled “Dependency Injection”Nimbus resolves controllers through its container, so both the constructor and each action can declare what they need.
Constructor Injection
Section titled “Constructor Injection”Type-hint classes in the constructor. Concrete classes are built automatically; interfaces need a binding:
use App\Services\DatabaseProductRepository;use App\Services\ProductRepository;
$app->container()->bind(ProductRepository::class, DatabaseProductRepository::class);Method Injection
Section titled “Method Injection”Action parameters are resolved in this order:
- Route parameters, by name. A scalar parameter receives the string from the URL; a class-typed parameter goes through route model binding.
- The current
RequestandResponse, by type. - The container, for any other class type, including form requests and typed inputs, which are validated before the action runs.
- The parameter’s default value, or
nullwhen it is nullable.
If none of these applies, the request fails with a RuntimeException naming the parameter.
use Nimbus\Http\RequestContext;use Pam\Http\Request;use Psr\Log\LoggerInterface;
public function show(string $product, Request $request, LoggerInterface $logger, RequestContext $context): array{ $logger->info('Product {id} viewed', ['id' => $product, 'tenant' => $context->get('tenant')]);
return ['id' => (int) $product, 'expand' => $request->getQuery('expand')];}The Service Container
Section titled “The Service Container”The container decides how long each object lives. In a persistent worker that choice matters more than in PHP-FPM, because “the whole process” means thousands of requests:
$container = $app->container();
$container->bind(ReportBuilder::class); // a new instance every time$container->singleton(PriceCalculator::class); // one instance per worker$container->scoped(CurrentUser::class); // one instance per request$container->instance(Clock::class, new SystemClock()); // this exact object, per worker| Lifetime | Created | Use it for |
|---|---|---|
bind() (or no binding) |
Every resolution | Controllers, short-lived services. |
singleton() |
Once per worker | Stateless services, configuration, connection pools. |
scoped() |
Once per request, discarded when it ends (even on exceptions) | The current user, tenant, unit of work. |
instance() |
Already built | Objects you construct at boot. |
Resolving a scoped binding outside a request throws a LogicException. Register bindings while the application boots; the container should not change once requests are served.
Service Providers
Section titled “Service Providers”Packages and larger applications group bindings in service providers. A provider implements Pam\Contracts\Package\ServiceProviderInterface: register() runs when you add it, and boot() runs once, just before the first request:
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Billing\Gateway;use App\Billing\StripeGateway;use Nimbus\App;use Pam\Contracts\Http\ApplicationInterface;use Pam\Contracts\Package\ServiceProviderInterface;
final class BillingServiceProvider implements ServiceProviderInterface{ public function register(ApplicationInterface $application): void { if ($application instanceof App) { $application->container()->singleton(Gateway::class, StripeGateway::class); } }
public function boot(ApplicationInterface $application): void { }}$app->provider(new App\Providers\BillingServiceProvider());new App() also discovers the providers that installed packages declare, unless you pass discoverPackages: false.