Anvyr Docs
Documentation menu Anvyr Loom 1.x
Anvyr Loom

Version 1.x

← All documentation

GuideAnvyr Loom 1.xDeveloper

Bind and resolve services

Factories, shared instances, aliases, and constructor injection.

On this page

Register an explicit factory

The application container accepts callable factories. Register services during a module's register() phase or your application bootstrap.

use Anvyr\Loom\Core\Application;

$app->bind(DateTimeZone::class, static fn () => new DateTimeZone('UTC'));
$timezone = $app->make(DateTimeZone::class);

bind() invokes its factory on each resolution. Capture the application explicitly if a factory needs to resolve other dependencies; the factory is not passed the container automatically.

Share an instance

$app->singleton(DateTimeZone::class, static fn () => new DateTimeZone('UTC'));

singleton() creates the instance on first resolution and reuses it within that application container. To register an existing object, use instance():

$app->instance(DateTimeZone::class, new DateTimeZone('UTC'));

Avoid capturing request-specific or tenant-specific mutable state in a shared service unless its lifecycle explicitly accounts for it.

Constructor injection

make() first checks registered services. If a concrete class exists without a binding, it attempts constructor autowiring. Class-typed dependencies can be resolved recursively; scalar values and interfaces generally need an explicit binding or a suitable default.

This lets controllers receive dependencies through their constructors while keeping service creation in one visible place.

Use aliases deliberately

$app->singleton('clock.timezone', static fn () => new DateTimeZone('UTC'));
$app->alias('clock.timezone', DateTimeZone::class);

The first argument is the registered service key; the second is the alias. get() retrieves a registered service, while make() can also attempt autowiring.

See Application for resolution and error behavior.

Continue readingBuild with modules