PHP code example of lss / yacontainer

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

    

lss / yacontainer example snippets


$aliases = [
    MyFoo::class => MyCachedFoo::class,
    MyBarInterface::class => MyBarImplementation::class
];
$container = new Container($_ENV, $aliases);

class DatabaseConnection extends \PDO {
    public function __construct(string $databaseDSN, string $databaseUser, string $databasePassword) 
    {
        $options = ['charset' => 'utf8',PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
        parent::__construct($databaseDSN, $databaseUser, $databasePassword, $options);
    }

    // ... other utility functions    
}

$container = new Container(['databaseDSN' => 'mysql:host=localhost;dbname=theDBName', 'databaseUser' => 'theUserName', 'databasePassword' => 'thePassword']);
$databaseConnection = $container->get(DatabaseConnection::class);

$container->addScalar('maximumPassengers', function (Configuration $config) {
    return $config->getMaximumPassengers();
});

 $fuelPercent = 75;
 $container = new Container();
 $container->addFactory(Car::class, function (EngineInterface $engine) use ($fuelPercent): Car {
     $result = new Car($engine);
     $result->refuel($fuelPercent);
     return $result;
 });

$container->setShouldShare(function (string $className): bool { return $className !== Car::class; });

$container->setShouldShare(function (string $className): bool { return false; });

$car = $container->get(Car::class);
$container->forget(Car::class);
$aDifferentCar = $container->get(Car::class);

class Psr11ContainerException extends \InvalidArgumentException implements Psr\Container\ContainerExceptionInterface {}

class Psr11Container implements Psr\Container\ContainerInterface {
    public __construct(private LSS\Container $wrapped) {}
    
    public function get(string $id) {
        try {
            return $this->wrapped->get($id);
        } catch (\Throwable $ex) {
            throw new Psr11ContainerException('Cannot build ' . $id, 0, $ex);
        }
    }
    
    public function has(string $id): bool 
    {
        return $this->wrapped->has($id);
    }
}