PHP code example of solophp / container

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

    

solophp / container example snippets


use Solo\Container;

// Create a new container
$container = new Container();

// Register a service
$container->set('database', function($container) {
    return new Database('localhost', 'mydb', 'user', 'pass');
});

// Bind an interface to a concrete implementation
$container->bind(LoggerInterface::class, FileLogger::class);

// Get a service
$db = $container->get('database');

class UserRepository
{
    public function __construct(
        private Database $database,
        private LoggerInterface $logger
    ) {}
}

// The container will automatically resolve Database and LoggerInterface
$userRepo = $container->get(UserRepository::class);

$container = new Container([
    'config' => fn() => new Config('config.php'),
    'cache' => fn($c) => new Cache($c->get('config')),
]);

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