PHP code example of franco2911 / avresticontainer

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

    

franco2911 / avresticontainer example snippets




use Avresticontainer\Container;

$container = Container::getInstance();

$container->bind('config', function() {
    return new class {
        public function get($key) {
            return $key;
        }
    };
});

$config = $container->make('config');
echo $config->get('example_key');  // Outputs: example_key

$container->singleton('config', function() {
    return new class {
        public $value = 'singleton_value';
    };
});

$config1 = $container->make('config');
$config2 = $container->make('config');

$config1->value = 'new_value';

echo $config2->value;  // Outputs: new_value

$container->addDefinitions([
    'config' => function() {
        return new Config(['db_host' => '127.0.0.1', 'db_name' => 'my_database']);
    },
    'database' => function($container) {
        return new DatabaseConnection($container->make('config'));
    },
    'simple.value' => 'This is a simple value'
]);

$config = $container->make('config');
$database = $container->make('database');
$simpleValue = $container->make('simple.value');

$container->bind('original', function() {
    return new class {
        public function getValue() {
            return 'original value';
        }
    };
});

$container->alias('original', 'alias');

$original = $container->make('alias');
echo $original->getValue();  // Outputs: original value

class DependencyA {
    public function getValue() {
        return 'valueA';
    }
}

class DependencyB {
    protected $dependencyA;

    public function __construct(DependencyA $dependencyA) {
        $this->dependencyA = $dependencyA;
    }

    public function getDependencyValue() {
        return $this->dependencyA->getValue();
    }
}

$container->bind(DependencyA::class);
$container->bind(DependencyB::class);

$dependencyB = $container->make(DependencyB::class);
echo $dependencyB->getDependencyValue();  // Outputs: valueA