PHP code example of kynetcode / wpzylos-container

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

    

kynetcode / wpzylos-container example snippets


use WPZylos\Framework\Container\Container;

$container = new Container();

// Bind a singleton (shared instance)
$container->singleton(DatabaseConnection::class, fn() => new DatabaseConnection());

// Bind a factory (new instance each time)
$container->bind(Logger::class, fn() => new Logger());

// Auto-wiring (automatic dependency resolution)
$container->bind(UserService::class);

// Resolve
$db = $container->get(DatabaseConnection::class);
$logger = $container->get(Logger::class);
$userService = $container->get(UserService::class);

// Registered once, shared everywhere
$container->singleton(Config::class, fn() => new Config('config.php'));

$config1 = $container->get(Config::class);
$config2 = $container->get(Config::class);
// $config1 === $config2

// New instance every time
$container->bind(Request::class, fn() => new Request());

$req1 = $container->get(Request::class);
$req2 = $container->get(Request::class);
// $req1 !== $req2

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

// Container automatically resolves dependencies
$container->bind(UserService::class);
$userService = $container->get(UserService::class);

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

$container->tag([EmailNotifier::class, SlackNotifier::class], 'notifiers');

$notifiers = $container->tagged('notifiers');
foreach ($notifiers as $notifier) {
    $notifier->send($message);
}

$container->singleton(Connection::class, fn() => new Connection());
$container->alias('db', Connection::class);

$db = $container->get('db'); // Same as get(Connection::class)

// Check if bound
$container->has(Logger::class); // true

// Remove a service
$container->forget(Logger::class);

// List all registered keys
$keys = $container->keys();