1. Go to this page and download the library: Download borschphp/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/ */
borschphp / container example snippets
use Borsch\Container\Container;
$container = new Container();
// Add your dependencies
$container->set('db', fn() => new PDO('mysql:host=localhost;dbname=mydb', 'user', 'password'));
// Retrieve your dependencies
$db = $container->get('db');
use Borsch\Container\Container;
$container = new Container();
$container
->set('db', PDO::class)
->addParameter('mysql:host=localhost;dbname=mydb')
->addParameter('user')
->addParameter('password');
$db = $container->get('db');
use Borsch\Container\Container;
$container = new Container();
$container
->set('logger', fn() => new Logger())
->cache(true);
$logger1 = $container->get('logger');
$logger2 = $container->get('logger');
// $logger1 and $logger2 are the same instances
class MyApp
{
public function __construct(
protected Logger $logger
) {}
}
use Borsch\Container\Container;
$container = new Container();
$container->set(Logger::class, function () {
$logger = new Logger('app');
$logger->pushHandler(new StreamHandler('path/to/log/file.log'));
return $logger;
})-> cache(true);
$container->set(MyApp::class);
$app = $container->get(MyApp::class);
// $app is instantiated with the logger from entry Logger::class
use Borsch\Container\Container;
$container = new Container();
$container->set(PDO::class, function () {
$pdo = new PDO('sqlite:/path/to/my/database.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
})->cache(true);
$container->set(
CacheInterface::class,
// PDO instance defined upper will be injected here as parameter
fn(PDO $pdo) => new PdoAdapter($pdo)
)->cache(true);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.