PHP code example of tflori / dependency-injector

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

    

tflori / dependency-injector example snippets



$container->share('databaseConnection', function () {
    return new DatabaseConnection();
});
$container->add('myService', function () use ($container) {
    return new MyService($container->get('databaseConnection'));
});


DI::share('databaseConnection', function () {
    return new DatabaseConnection();
});
DI::add('myService', function () {
  return new MyService(); // we can access DI::get('databaseConnection') within this class now
});


DI::share('databaseConnection', function () {
    return m::mock(DatabaseConnection::class);
});

DI::get('databaseConnection')->shouldReceive('query'); 
// ...


$feed = DI::make(SomeFeed::class, $_GET['id']);
// equals to  new SomeFeed($_GET['id']);


DI::instance(SomeFeed::class, m::mock(SomeFeed::class));
$feedMock = DI::make(SomeFeed::class, $_GET['id']);


DI::instance('config', (object)[
    'database' => (object)[
        'dsn' => 'mysql://whatever',
        'user' => 'john',
        'password' => 'does_secret',
    ]
]);


DI::share(Config::class, Config::class);
DI::alias(Config::class, 'config');
DI::alias(Config::class, 'cfg'); 


// pass some statics
DI::share('session', Session::class)
    ->addArguments('app-name', 3600, true);
new Session(DI::has('app-name') ? DI::get('app-name') : 'app-name', 3600, true);

// pass dependencies
DI::share('database', Connection::class)
    ->addArguments('config');
new Connection(DI::has('config') ? DI::get('config') : 'config');

// pass a string that is defined as dependency
DI::add('view', View::class)
    ->addArguments(new StringArgument('default-layout'));
new View('default-layout');


DI::share('cache', Redis::class)
    ->addMethodCall('connect', 'localhost', 4321, 1);

// you can also bypass resolving the dependency
DI::add('view', View::class)
    ->addMethodCall('setView', new StringArgument('default-view'));


DI::add('view', View::class);
$view = DI::get('view', 'login');
new View('login');


use App\Http\Controller;
use DependencyInjector\Factory\NamespaceFactory;
use DependencyInjector\DI;

$request = (object)$_SERVER;
DI::add(Controller::class, (new NamespaceFactory(DI::getContainer(), Controller::class))
    ->addArguments(DI::getContainer()));
DI::get(Controller\UserController::class, $request);

// equals to
new Controller\UserController(DI::getContainer(), $request);


DI::share('ViewHelper', (new NamespaceFactory(DI::getContainer(), App\View\Helper::class))
    ->addArguments(DI::getContainer()));
DI::get(App\View\Helper\Url::class);


DI::add('calculator', Calculator::class);

DI::get('calculator', 'rad');
Calculator::getInstance('rad');

DI::get('calculator', 'deg');
Calculator::getInstance('deg');


DI::share('database', function() {
    $config = DI::get('config');
    return new PDO($config->database->dsn, $config->database->username, $config->database->password);
});


class DatabaseFactory extends \DependencyInjector\Factory\AbstractFactory
{
    protected $shared = true; // false is default - so simple omit it for non shared factories or use share to define
    
    protected function build()
    {
        $dbConfig = $this->container->get('config')->database;
        return new PDO($dbConfig->dsn, $dbConfig->user, $dbConfig->password);
    }
}


class Config {
    private static $_instance;
    
    public $database = [
        'host' => 'localhost',
        'user' => 'john',
        'password' => 'does.secret',
        'database' => 'john_doe'
    ];
    
    public $redis = ['host' => 'localhost'];
    
    private function __construct() {
        // maybe some logic to change the config or initialize variables
    }
    
    public static function getInstance() {
        if (!self::$_instance) {
            self::$_instance = new Config();
        }
        return self::$_instance;
    }
}

DI::add('config', Config::class); // adds a SingletonFactory

function someStaticFunction() {
    // before
    if (empty(Config::getInstance()->database['host'])) {
        throw new Exception('No database host configured');
    }
    
    // now
    if (empty(DI::get('config')->database['host'])) {
        throw new Exception('No database host configured');
    }
}


DI::set('database', function() {
    $dbConfig = DI::get('config')->database;
    
    $mysql = new mysqli($dbConfig['host'], $dbConfig['user'], $dbConfig['password'], $dbConfig['database']);
    
    if (!empty($mysql->connect_error)) {
        throw new Exception('could not connect to database (' . $mysql->connect_error . ')');
    }
    
    return $mysql;
});

function someStaticFunction() {
    // before it maybe looked like this
    $mysql = MyApp::getDatabaseConnection();
    
    // now
    $mysql = DI::get('database');
    
    $mysql->query('SELECT * FROM table');
}


class ApplicationTest extends TestCase {
    public function testSomeStaticFunction() {
        // prepare the mock
        $mock = $this->getMock(mysqli::class);
        $mock->expects($this->once())->method('query')
            ->with('SELECT * FROM table');
        
        // overwrite the dependency
        DI::instance('database', $mock);
            
        someStaticFunction();
    }
}


/**
 * @method static Config config()
 * @method static mysqli database() 
 */
class DI extends \DependencyInjector\DI {}


/** 
 * @property Config config
 * @method Config config()
 */
class Container extends \DependencyInjector\Container {}