1. Go to this page and download the library: Download denosyscore/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/ */
denosyscore / container example snippets
use Denosys\Container\Container;
$container = new Container();
// Bind an interface to a concrete class
$container->bind(LoggerInterface::class, FileLogger::class);
// Bind as a singleton
$container->singleton(CacheInterface::class, RedisCache::class);
// Resolve — dependencies are injected automatically
$logger = $container->get(LoggerInterface::class);
$cache = $container->get(CacheInterface::class);
assert($cache === $container->get(CacheInterface::class)); // same instance
class OrderService
{
public function __construct(
private readonly PaymentGateway $payment,
private readonly InventoryRepository $inventory,
) {}
}
// PaymentGateway and InventoryRepository are built and injected automatically
$service = $container->get(OrderService::class);
// Interface to concrete class
$container->bind(LoggerInterface::class, FileLogger::class);
// Factory closure
$container->bind(DatabaseConnection::class, function (Container $c) {
return new DatabaseConnection(config('db.dsn'));
});
$result = $container->scoped([
LoggerInterface::class => TestLogger::class,
], function () use ($container, $order) {
// OrderService receives TestLogger inside this scope
return $container->get(OrderService::class)->process($order);
});
// LoggerInterface is back to its original binding here
$proxy = $container->lazy(ReportGenerator::class);
// ReportGenerator is NOT instantiated yet
$report = $proxy->generate($data);
// Resolved on first call, then reused
$spy = $container->spy(PaymentGateway::class);
// ... exercise code that uses PaymentGateway ...
echo $spy->getResolutionCount(); // number of times resolved
echo $spy->getAverageResolutionTime(); // average ms per resolution
echo $spy->getTotalResolutionTime(); // total ms across all resolutions
$summary = $spy->getSummary();
// ['abstract' => ..., 'resolution_count' => ..., 'average_resolution_time' => ...]