PHP code example of fatjon-lleshi / antares-container

1. Go to this page and download the library: Download fatjon-lleshi/antares-container library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fatjon-lleshi / antares-container example snippets


use Antares\Container\Container;

class Logger {}

class UserService {
    public function __construct(
        private readonly Logger $logger
    ) {}
}

$container = new Container();
$service = $container->make(UserService::class);

interface LoggerInterface {}
class FileLogger implements LoggerInterface {}

$container = new Container();
$container->bind(LoggerInterface::class, FileLogger::class);

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

$container->singleton(Database::class, function(Container $container) {
    return new Database(
        host: $_ENV['DB_HOST'],
        port: (int) $_ENV['DB_PORT'],
        name: $_ENV['DB_NAME'],
    );
});

$db = $container->make(Database::class);

class Cache {}

class Repository {
    public function __construct(
        private readonly Database $db,
        private readonly Cache $cache,
    ) {}
}

$repository = $container->make(Repository::class);

use Antares\Container\ContainerException;

try {
    $container->make(LoggerInterface::class);
} catch (ContainerException $e) {
    echo $e->getMessage();
}

class A {
    public function __construct(public B $b) {}
}
class B {
    public function __construct(public A $a) {}
}

$container->make(A::class); // throws ContainerException: Circular dependency detected

class Mailer {
    public function __construct(
        public readonly string $host,
        public readonly int $port,
    ) {}
}

$container->singleton(Mailer::class, fn() => new Mailer(
    host: $_ENV['MAIL_HOST'],
    port: (int) $_ENV['MAIL_PORT'],
));