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']);
// 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);
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 {}