PHP code example of temant / container

1. Go to this page and download the library: Download temant/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/ */

    

temant / container example snippets


use Temant\Container\Container;

$container = new Container();

// Register a shared (singleton) service
$container->set(Logger::class, fn() => new Logger('/var/log/app.log'));

// Retrieve it -- same instance every time
$logger = $container->get(Logger::class);

use Temant\Container\Container;

// Default: autowiring enabled, autowired instances cached
$container = new Container();

// Disable autowiring (explicit registration only)
$container = new Container(autowiringEnabled: false);

// Autowiring enabled but instances not cached (new instance each time)
$container = new Container(autowiringEnabled: true, cacheAutowire: false);

$container->set(DatabaseConnection::class, function (ContainerInterface $c) {
    return new DatabaseConnection(
        host: 'localhost',
        name: 'mydb',
    );
});

// Alias for readability
$container->singleton(Mailer::class, fn(ContainerInterface $c) => new Mailer(
    $c->get(DatabaseConnection::class),
));

$container->factory(RequestId::class, fn() => new RequestId(bin2hex(random_bytes(16))));

$id1 = $container->get(RequestId::class); // unique
$id2 = $container->get(RequestId::class); // different instance

$config = new AppConfig(debug: true, timezone: 'UTC');

$container->instance(AppConfig::class, $config);

$container->multi([
    Logger::class    => fn() => new Logger(),
    Mailer::class    => fn() => new Mailer(),
    Cache::class     => fn() => new RedisCache(),
]);

// Only registers if Logger::class is not already in the container
$container->setIf(Logger::class, fn() => new FileLogger());
$container->singletonIf(Logger::class, fn() => new FileLogger()); // alias for setIf()

// Same for factories and instances
$container->factoryIf(RequestId::class, fn() => new RequestId(uniqid()));
$container->instanceIf(AppConfig::class, new AppConfig());

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

$container->set(FileLogger::class, fn() => new FileLogger('/var/log/app.log'));

// Resolves FileLogger
$logger = $container->get(LoggerInterface::class);

$container->alias('db', DatabaseConnection::class);

$db = $container->get('db'); // same as get(DatabaseConnection::class)

$container->when(UserController::class)
          ->needs(LoggerInterface::class)
          ->give(FileLogger::class);

$container->when(AdminController::class)
          ->needs(LoggerInterface::class)
          ->give(ConsoleLogger::class);

// UserController gets FileLogger, AdminController gets ConsoleLogger
$userCtrl  = $container->get(UserController::class);
$adminCtrl = $container->get(AdminController::class);

$container->when(PaymentService::class)
          ->needs(LoggerInterface::class)
          ->give(fn(ContainerInterface $c) => new FileLogger('/var/log/payments.log'));

$container->set(ConsoleLogger::class, fn() => new ConsoleLogger());
$container->set(FileLogger::class, fn() => new FileLogger('/var/log/app.log'));

$container->tag(ConsoleLogger::class, 'loggers');
$container->tag(FileLogger::class, 'loggers');

// Returns [ConsoleLogger instance, FileLogger instance]
$loggers = $container->tagged('loggers');

$container->set(Logger::class, fn() => new Logger());

$container->extend(Logger::class, function (object $logger, ContainerInterface $c) {
    $logger->pushHandler(new StreamHandler('/var/log/debug.log'));
    return $logger;
});

$container->inflect(LoggerAwareInterface::class, function (object $service, ContainerInterface $c) {
    $service->setLogger($c->get(LoggerInterface::class));
});

// Any resolved service implementing LoggerAwareInterface
// will automatically have setLogger() called.
$service = $container->get(MyService::class); // logger injected if MyService implements LoggerAwareInterface

// Fire for a specific service ID
$container->resolving(Logger::class, function (object $logger, ContainerInterface $c) {
    // Called when Logger is being resolved (before it's returned)
});

$container->afterResolving(Logger::class, function (object $logger, ContainerInterface $c) {
    // Called after Logger is fully resolved (after extenders + inflectors)
});

// Fire for every resolution (global)
$container->resolving(function (object $service, ContainerInterface $c) {
    // Called for every service resolution
});

$container->afterResolving(function (object $service, ContainerInterface $c) {
    // Called after every service resolution
});

use Temant\Container\Container;
use Temant\Container\ServiceProviderInterface;

class DatabaseServiceProvider implements ServiceProviderInterface
{
    public function register(Container $container): void
    {
        $container->singleton(PDO::class, fn() => new PDO(
            'mysql:host=localhost;dbname=myapp', 'root', '',
        ));
    }

    public function boot(Container $container): void
    {
        // Runs after all providers are registered.
        // Safe to resolve other services here.
    }
}

$container->register(new DatabaseServiceProvider());

// Call boot() after all providers are registered
$container->boot();

class UserRepository
{
    public function __construct(
        private readonly DatabaseConnection $db,
        private readonly Logger $logger,
    ) {}
}

// No registration needed -- both UserRepository and its
// dependencies are resolved automatically.
$repo = $container->get(UserRepository::class);

$container->setAutowiring(false);
$container->hasAutowiring(); // false

class LoggerAggregate
{
    public function __construct(LoggerInterface ...$loggers) {}
}

$container->set(FileLogger::class, fn() => new FileLogger());
$container->set(ConsoleLogger::class, fn() => new ConsoleLogger());

// Tag both with the interface name
$container->tag(FileLogger::class, LoggerInterface::class);
$container->tag(ConsoleLogger::class, LoggerInterface::class);

// Both loggers are injected
$aggregate = $container->get(LoggerAggregate::class);

$result = $container->call(function (Logger $logger, Mailer $mailer) {
    $logger->info('Sending mail...');
    return $mailer->send('[email protected]', 'Hi!');
});

// With named overrides
$result = $container->call(
    fn(Logger $logger, string $message) => $logger->info($message),
    ['message' => 'Custom message'],
);

$result = $container->call('App\Controller\UserController@show', ['id' => 42]);

$controller = $container->get('App\Controller\UserController');
$result = $container->call([$controller, 'show'], ['id' => 42]);

// Always returns a new Foo, even if Foo is registered as a singleton
$foo = $container->make(Foo::class);

// With parameter overrides
$mailer = $container->make(Mailer::class, [
    'transport' => 'smtp',
    'host'      => 'mail.example.com',
]);

use Temant\Container\LazyProxy;

$container->lazy(HeavyService::class, function (ContainerInterface $c) {
    // This runs only when a method is called on the proxy
    return new HeavyService($c->get(Database::class));
});

$service = $container->get(HeavyService::class); // Returns a LazyProxy -- factory NOT called
$service->doWork();                               // NOW the factory runs, then doWork() is called

$proxy = $container->get(HeavyService::class);

$proxy->isInitialized(); // false -- not yet created
$proxy->getTarget();     // forces creation, returns real instance
$proxy->isInitialized(); // true

$parent = new Container();
$parent->set(Logger::class, fn() => new FileLogger());

$child = $parent->createChild();
$child->set(Logger::class, fn() => new ConsoleLogger()); // overrides parent

$child->get(Logger::class);  // ConsoleLogger
$parent->get(Logger::class); // FileLogger (unaffected)

// Falls back to parent for entries not in the child
$parent->set(Mailer::class, fn() => new Mailer());
$child->get(Mailer::class); // resolved from parent

$child->getParent();            // returns parent Container
$parent->getParent();           // null (root container)
$child->createChild();          // grandchild

// Check if an entry exists (considers bindings, parent, and autowiring)
$container->has(Logger::class); // true

// Remove an entry (definitions, bindings, cached instances, extenders)
$container->remove(Logger::class);

// Clear everything (all registrations, state, and frozen flag)
$container->clear();

// Clear only cached instances (keeps definitions)
// Useful in tests or long-running workers (Swoole, RoadRunner)
$container->flushInstances();

$container->freeze();

$container->isFrozen(); // true

$container->set(Foo::class, fn() => new Foo());
// throws ContainerException: "Cannot modify a frozen container."

// clear() resets the frozen state
$container->clear();
$container->isFrozen(); // false

$container->warmUp(); // invokes all shared factories, populates instance cache
$container->freeze(); // lock for production

// List all registered service IDs
$container->keys(); // ['App\Logger', 'App\Mailer', ...]

// Structured snapshot of all registrations
$container->all();
// Returns: ['shared' => [...], 'factories' => [...], 'instances' => [...], 'bindings' => [...], 'tags' => [...]]

// Specific registration types
$container->allShared();
$container->allFactories();
$container->allInstances();
$container->allBindings();

$container->set(Logger::class, fn() => new FileLogger());
$container->tag(Logger::class, 'loggers');
$container->extend(Logger::class, fn($l) => $l);

$def = $container->getDefinition(Logger::class);
// [
//     'id'           => 'App\Logger',
//     'resolvedId'   => 'App\Logger',
//     'type'         => 'shared',         // 'shared', 'factory', 'instance', or null
//     'binding'      => null,             // target if this ID is a binding/alias
//     'tags'         => ['loggers'],
//     'hasExtenders' => true,
// ]

// Returns null for unregistered IDs
$container->getDefinition('unknown'); // null

use Psr\Container\NotFoundExceptionInterface;
use Psr\Container\ContainerExceptionInterface;

try {
    $service = $container->get('unknown');
} catch (NotFoundExceptionInterface $e) {
    // Entry not found
} catch (ContainerExceptionInterface $e) {
    // Other container error
}