PHP code example of marcosdipaolo / container

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

    

marcosdipaolo / container example snippets


use MDP\Container\Container;

$container = new Container();

// Automatic wiring
$myService = $container->get(MyService::class);

// Register bindings
$container->singleton(DatabaseInterface::class, MySQLDatabase::class);
$container->transient(Logger::class, FileLogger::class);
$container->factory('timestamp', fn() => time());

// Get instances
$db = $container->get(DatabaseInterface::class);
$logger = $container->get(Logger::class);
$time = $container->get('timestamp');

class UserRepository
{
    public function __construct(private DatabaseConnection $db) {}
}

class UserService
{
    public function __construct(private UserRepository $repo) {}
}

// No registration needed!
$userService = $container->get(UserService::class);
// All dependencies are automatically injected

$container->singleton(Logger::class, FileLogger::class);

$logger1 = $container->get(Logger::class);
$logger2 = $container->get(Logger::class);

assert($logger1 === $logger2); // True

$container->transient(Request::class, HttpRequest::class);

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

assert($req1 !== $req2); // True - different instances

$container->factory('config', function(Container $container) {
    return new Config(getenv('CONFIG_PATH'));
});

// Created fresh every time via the factory function
$config = $container->get('config');

interface CacheStoreInterface {}
class RedisCache implements CacheStoreInterface {}

$container->singleton(CacheStoreInterface::class, RedisCache::class);

$cache = $container->get(CacheStoreInterface::class);
assert($cache instanceof RedisCache); // True

$container->set('pdo', function(Container $container) {
    return new PDO('sqlite::memory:');
});

// With more control - access other services
$container->set(UserRepository::class, function(Container $container) {
    $db = $container->get('pdo');
    $logger = $container->get(Logger::class);
    return new UserRepository($db, $logger);
});

$container = new Container();

$container->set('name', ConcreteClass::class);
$container->set('factory', fn($c) => new Thing(), 'transient');

$container->singleton(Database::class, MySQLDatabase::class);

$container->transient(Request::class, HttpRequest::class);

$container->factory('timestamp', fn($c) => time());

$service = $container->get(MyService::class);

if ($container->has('config')) {
    $config = $container->get('config');
}

$service = $container->resolve(MyService::class);
// All constructor dependencies are wired automatically

$container->clearSingletons();
// Next get() will create fresh instances

$container->clearReflectionCache();

class Service
{
    public function __construct($dependency) {} // No type hint!
}

$container->get(Service::class);
// ContainerException: Cannot resolve "Service" - constructor parameter 
// "dependency" is missing a type hint. Add a type declaration or use 
// a factory function for explicit wiring.

class Service
{
    public function __construct(TypeA|TypeB $dependency) {}
}

$container->get(Service::class);
// ContainerException: Cannot resolve "Service" - constructor parameter 
// "dependency" has a union type. Union types are ambiguous for automatic 
// resolution. Use a factory function instead.

class ServiceA { public function __construct(ServiceB $b) {} }
class ServiceB { public function __construct(ServiceA $a) {} }

$container->get(ServiceA::class);
// CircularDependencyException: Circular dependency detected: 
// ServiceA -> ServiceB -> ServiceA

class Service
{
    public function __construct(string $name) {} // No default value
}

$container->get(Service::class);
// ContainerException: Cannot resolve "Service" - constructor parameter 
// "name" is a builtin type with no default value. Use a factory function 
// for custom wiring.

// First call: reflection overhead
$service = $container->get(Service::class);

// Subsequent calls: cached reflection
$service2 = $container->get(Service::class);

$container->clearReflectionCache();

// Good - database connection created once
$container->singleton(PDOConnection::class, function($c) {
    return new PDO('mysql:host=localhost', 'user', 'pass');
});

// Poor - creates new connection for every request
$container->transient(PDOConnection::class, PDOConnection::class);