PHP code example of bayfrontmedia / container

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

    

bayfrontmedia / container example snippets


// Set a service with no dependencies

$container->set('Fully\Namespaced\ClassName', function () {
    return new ClassName();
});

// Set a service with dependencies

$container->set('Fully\Namespaced\ClassName', function (ContainerInterface $container) {
    $dependency = $container->get('Fully\Namespaced\Dependency');
    return new ClassName($dependency);
});

// Any type of value can be set, then used as a parameter

$container->set('classname_config', [
    // Config array
]);

$container->set('Fully\Namespaced\ClassName', function (ContainerInterface $container) {
    $config = $container->get('classname_config');
    return new ClassName($config);
});

// Preexisting class instances can be set without using an anonymous function

$class = new ClassName();
$container->set('ClassName', $class);

$entries = $container->getEntries();

$service = $container->get('Fully\Namespaced\ClassName');


class ClassName {

    protected $service;
    protected $config;
    
    public function __construct(AnotherService $service, array $config)
    {
        $this->service = $service;
        $this->config = $config;
    }

}

$instance = $container->make('Fully\Namespaced\ClassName', [
    'config' => []
]);

if ($container->has('Fully\Namespaced\ClassName')) {
    // Do something
}

$container->remove('Fully\Namespaced\ClassName');

$container->setAlias('alias', 'Fully\Namespaced\ClassName');

$container->setAlias('Fully\Namespaced\Implementation', 'Fully\Namespaced\Interface');

$aliases = $container->getAliases();

if ($container->hasAlias('alias')) {
    // Do something
}

$container->removeAlias('alias');