Back to Portfolio

Sefra Container Plugin

Methods

bind(string $abstract, $concrete = null, bool $shared = false): void

Register a binding with the container.

Parameters:

Returns: void

Example:

$container->bind(LoggerInterface::class, FileLogger::class);
$container->bind(ApiClient::class, fn($c) => new ApiClient());

singleton(string $abstract, $concrete = null): void

Register a singleton binding (only one instance will be created).

Parameters:

Returns: void

Example:

$container->singleton(DatabaseService::class);
$container->singleton(CacheService::class, fn($c) => new RedisCache());

instance(string $abstract, object $instance): void

Bind an existing instance to the container.

Parameters:

Returns: void

Example:

$config = new Config(['debug' => true]);
$container->instance(ConfigInterface::class, $config);

resolve(string $abstract): mixed

Resolve a service from the container.

Parameters:

Returns: mixed - The resolved instance

Example:

$logger = $container->resolve(LoggerInterface::class);

get(string $abstract): mixed

Alias for resolve(). Resolve a service from the container.

Parameters:

Returns: mixed - The resolved instance

Example:

$logger = $container->get(LoggerInterface::class);
$service = $container->get(MyService::class);

has(string $id): bool

Check if a binding exists in the container.

Parameters:

Returns: bool - True if binding exists, false otherwise

Example:

if ($container->has(LoggerInterface::class)) {
    $logger = $container->resolve(LoggerInterface::class);
}

forbidContainerInjection(false): void

Prevent the forbidden container from being injected as a dependency.

Parameters: None

Returns: void

Example:

$container->forbidContainerInjection(false);

// This will now not throw an exception
class BadService {
    public function __construct(Container $container) {}
}