1. Go to this page and download the library: Download vanilla/garden-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/ */
vanilla / garden-container example snippets
class Controller
{
public function __construct(Model $model)
{
}
}
class Model
{
public function __construct(PDO $db)
{
}
}
$controller = new Controller(new Model(new PDO($dsn, $username, $password);
$dic = new Container();
$controller = $dic->get("Controller"); // dependencies magically wired up
$dic = new Container();
$dic->rule("PDO")->setConsructorArgs([$dsn, $username, $password]);
class Job
{
public function __construct(Envornment $env, $name, Logger $log)
{
}
}
$dic = new Container();
$dic->rule("Job")->setConstructorArgs(["job name"]);
$job = $dic->get("Job");
$dic->defaultRule()->setShared(true);
// Now all objects are shared by default.
class Config
{
public function __construct($path)
{
$this->data = json_decode(file_get_contents($path), true);
}
public function get($key)
{
return $this->data[$key];
}
}
$dic = new Container();
$dic->rule(Config::class)
->setShared(true)
->setConstructorArgs(["../config.json"])
->rule(PDO::class)
->setConstructorArgs([
new Reference([Config::class, "dsn"]),
new Reference([Config::class, "user"]),
new Reference([Config::class, "password"]),
]);
$pdo = $dic->get(PDO::class);
class Dispatcher
public function __construct(Container $dic) {
$this->dic = $dic;
}
public function dispatch($url) {
$args = explode('/', $url);
$controllerName = ucfirst(array_shift($args)).'Controller';
$method = array_shift($args) ?: 'index';
$controller = $this->dic->get($controllerName);
return $this->dic->call([$controller, $method], $args)
}
}
$dic = new Container();
$dic->setInstance(Container::class, $dic);
$dispatcher = $dic->get(Dispatcher::class);
$dispatcher->dispatch(...);
class Task
{
public function __construct(LoggerInterface $log)
{
}
}
class Item
{
public function __construct(AbstractLogger $log)
{
}
}
$dic = new Container();
$dic->rule(LoggerInterface::class)
->setClass("SysLogger")
->setShared(true)
->addAlias(AbstractLogger::class);
$task = $dic->get(Task::class);
$item = $dic->get(Item::class);
// Both logs will point to the same shared instance.
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.