PHP code example of mcustiel / php-simple-di

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

    

mcustiel / php-simple-di example snippets


use Mcustiel\DependencyInjection\DependencyInjectionService;

$dependencyInjectionService = new DependencyInjectionService();
// ...
$dbConfig = loadDbConfig();
$cacheConfig = loadCacheConfig();
$dependencyInjectionService->register('dbConnection', function() use ($dbConfig) {
    return new DatabaseConnection($dbConfig);
});
$dependencyInjectionService->register('cache', function() use ($cacheConfig) {
    return new CacheManager($cacheConfig);
});

$cacheManager = $dependencyInjectionService->get('cache');

$dependencyInjectionService->add('dbConnection', function() use ($dbConfig) {
    return new DatabaseConnection($dbConfig);
});
// or also you can make it explicit:
$dependencyInjectionService->register('cache', function() use ($cacheConfig) {
    return new CacheManager($cacheConfig);
}, true);

$instance1 = $dependencyInjectionService->get('cache');
$instance2 = $dependencyInjectionService->get('cache');
// $instance1 and $instance2 reference the same object

$dependencyInjectionService->register('dbConnection', function() use ($dbConfig) {
    return new DatabaseConnection($dbConfig);
}, false);

$instance1 = $dependencyInjectionService->get('cache');
$instance2 = $dependencyInjectionService->get('cache');
// $instance1 and $instance2 reference different objects

$dependencyInjectionService->add('config-loader', function() {
    return new SomeConfigLoaderService();
});

$dependencyInjectionService->add('config', function() {
    $injector = new DependencyInjectionService();
    $configLoader = $injector->get('config-loader');
    return $configLoader->load();
});

$dependencyInjectionService->add('dbConnection', function() {
    $injector = new DependencyInjectionService();
    $dbConfig = $injector->get('config');
    return new DatabaseConnection($dbConfig);
});

// Do this:
$dbConnection = $dependencyInjectionService->get('dbConnection');
$personDao = new PersonDao($dbConnection); // Pass the proper dependency
// Instead of doing this:
$personDao = new PersonDao($dependencyInjectionService); // This works but is heretic and makes a little kitten cry.