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->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);
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);
// 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