PHP code example of mmdm / sim-container

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

    

mmdm / sim-container example snippets

 
composer 



// to instance a container object
$container = new Container();
// here you can define your object and use them

// store a class
$container->set('log_cls', Logger::class);
// or simply store with Logger::class string
// alias will be the string from Logger::class
$container->set(Logger::class);
// or if you have some works to do and return a 
// new instance then use this
$container->set('alias of class', function (Container $c) {
    // do anything you need
    // ...
    
    // return a new instance of a class
    return new SomeClass();
});

// method injection
$container->set('log_cls', Logger::class, 'info');

// or with parameters
$container->set('log_cls', Logger::class, 'info', [
    'handler' => Handler::class,
    1 => '{level} - {other_parameter} - {message}',
]);

// retrieve a class
$container->get('log_cls');
// or
$container->get(NotStoredClass::class);

// retrieve new instance of a class
$container->make('log_cls');
// or
$container->make(NotStoredClass::class);

// check existence of a $abstract
$container->has('log_cls');
// or
$container->has(NotStoredClass::class);

// remove an $abstract
$container->unset('log_cls');
// or
$container->unset(NotStoredClass::class);

$container = Container::getInstance();

// then use all methods
$container->get($abstract);

//...

class YourOtherClass extends AnotherClass {
    use ContainerTrait;
    
    // other codes
}

$instance = new YourOtherClass();

// the difference is in [YourOtherClass] instead of [Container]
$instance->set($abstract, function (YourOtherClass $c) {
    // some code
});